java基础笔记12 - 网络编程

十二 网络编程

1.概述

直接间接的使用挽留过协议,与其他计算机实现数据的交换

俩问题:

  1. 如何定位对方的主机,定位到特定的进程应用 IP+Port
  2. 如何可靠的进行数据传输 OSI参考模型和TCP/IP参考模型+各层的协议

2. IP Port

2.1 ip

java中使用InetAddress类表示一个地址

try {
    InetAddress inet1 = InetAddress.getByName("192.168.0.1");
    System.out.println(inet1);

    //域名方式
    InetAddress inet2 = InetAddress.getByName("www.baidu.com");
    System.out.println(inet2.getHostName); //www.baidu.com
    sout(inet2.getHostAddress());//182.61.200.6

    //本机地址
    InetAddress localHost = InetAddress.getLocalHost();
            
} catch (UnknownHostException e) {
    e.printStackTrace();
}

2.2 port:

0-1023:预先定义的公用端口:http 80

1024-49151:自定义端口号,如tomcat 8080,Mysql 3306,oracle 1521

49152-95535:动态/私有端口

Socket=ip+port

3.网络协议

3.1 传输层

3.1.1 UDP

​ 不需要建立连接 (不可靠)

​ 每个数据大小限制在64Kb

​ 可以广播

3.1.2 TCP

​ 必须建立TCP连接,形成数据通道(三次握手)

​ TCP协议通信的两边分别为客户端和服务器端

​ 可以进行大数据量的传输

​ 完毕需要释放连接( 四次挥手)

通信

@Test
public void client(){
    Socket socket= null;
    OutputStream os= null;
    try {
        InetAddress inet = InetAddress.getByName("localhost");
        socket = new Socket(inet,8889);
        os = socket.getOutputStream();
        os.write("我是客户端mm".getBytes(StandardCharsets.UTF_8));
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        //全部需要先判空,再try-catch
       os.close();
       socket.close();
    }
}
 @Test
public void server(){
    ServerSocket ss = null;
    Socket socket = null;
    InputStream is = null;
    ByteArrayOutputStream baos= null;
    try {
        ss = new ServerSocket(8889);
        socket = ss.accept();
        is = socket.getInputStream();
        //不建议这样写
        //        byte[] buffer=new byte[1024];
        //        int len;
        //        while ((len=is.read(buffer))!=-1){
        //            String str=new String(buffer,0.len);
        //            System.out.println(str);
        //        }
        baos = new ByteArrayOutputStream();
        byte[] buffer=new byte[1024];
        int len;
        while ((len=is.read(buffer))!=-1){
            baos.write(buffer,0,len);
        }
        System.out.println(baos.toString());
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        //全部需要先判空,再try-catch
        baos.close();
        is.close();
        socket.close();
        ss.close();   
    }
}

posted @ 2022-03-09 20:32  荧惑微光  阅读(18)  评论(0编辑  收藏  举报