学习内容:P400-P424
- 软件结构
BS----通过浏览器访问数据
CS----通过客户端访问数据 - 网络通信协议
TCP/IP协议是最基本最广泛的协议
- 网络连接协议分类
TCP—需要两台设备进行3次握手确认,优点安全,不会出现数据丢失,缺点效率相比UPD慢
UDP—无序设备进行确认,直接发送请求,优点效率高,缺点不安全,可能会出现数据丢失 - IP
ipconfig,获取ipv4、ipv6相关信息
ping 连接通就可以像该主机发送信息
本机IP地址 127.0.0.1 localhost - 端口号
6.TCP
TCP通信代码服务器
public static void method05() throws IOException {
ServerSocket serve= new ServerSocket(8888);
Socket socket = serve.accept();
InputStream is = socket.getInputStream();
byte[] by = new byte[1024];
int len = is.read(by);
System.out.println(new String(by,0,len));
OutputStream os = socket.getOutputStream();
os.write("收到谢谢".getBytes());
socket.close();
serve.close();
}
TCP通信客户端
public static void method04() throws IOException {
Socket socket =new Socket("127.0.0.1",8888);
OutputStream os = socket.getOutputStream();
os.write("你好服务器".getBytes());
InputStream is = socket.getInputStream();
byte[] by = new byte[1024];
int len = is.read(by);
System.out.println(new String(by,0,len));
socket.close();
}
文件上传案例服务端
public static void method02() throws IOException {
ServerSocket ss = new ServerSocket(8889);
Socket socket = ss.accept();
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream("javaTest\\src\\April\\Apr22th\\write.txt");
int len= 0;
byte[] by = new byte[1024];
while ((len = is.read(by))!=-1){
fos.write(by,0,len);
}
OutputStream os = socket.getOutputStream();
os.write("收到谢谢".getBytes());
socket.close();
ss.close();
}
客户端
public static void method01() throws IOException {
InputStream fis = new FileInputStream("javaTest\\src\\April\\Apr22th\\read.txt");
Socket socket = new Socket("127.0.0.1", 8889);
OutputStream os = socket.getOutputStream();
int len = 0;
byte[] by = new byte[1024];
while ((len = fis.read(by))!= -1){
os.write(by,0,len);
}
len = 0;
InputStream is = socket.getInputStream();
byte[] by2 = new byte[1024];
while ((len = is.read(by2))!= -1){
os.write(by2,0,len);
}
socket.close();
}
函数式接口
//用于检测是否为函数式接口,只能由一个抽象方法
@FunctionalInterface
public interface LambdaDemo {
public abstract void method01();
}
public class LambdaDemoImpl implements LambdaDemo{
@Override
public void method01() {
System.out.println("我是函数式接口");
}
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
method06(new LambdaDemoImpl());
method06(new LambdaDemo() {
@Override
public void method01() {
System.out.println("我是密名内部类的方法");
}
});
method06(()->
System.out.println("我是密名内部类的方法2")
);
}
public static void method06(LambdaDemo ld){
ld.method01();
}
lambda可以当作参数传递,避免某些情况的性能浪费
函数式编程
- 常用的函数式接口:Supplier接口 生产型接口
public class Haha {
public static String getString(Supplier<String> s){
return s.get();
}
public static void main(String[] args) {
String name = getString(()->{
return "姓名";
});
String name2 = getString(()->"姓名");
System.out.println(name2);
}
}