Java foundation, how to use Socket based on TCP and UDP protocol

Specific code for the use of Java-based Socket

Use of Socket based on TCP protocol to simulate client sending data and server receiving data

    @Test
    public void client() throws IOException {
    
    

        //创建socket对象,指明服务器的ip和端口号
        InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
        Socket socket = new Socket(inetAddress,8899);

        //获取一个输出流,用于输出数据
        OutputStream outputStream = socket.getOutputStream();
        //写出数据
        outputStream.write("我是客户端大姐".getBytes());
        //资源的关闭
        outputStream.close();
        socket.close();
    }

    @Test
    public void server() throws IOException {
    
    
        
        //创建serverSocket,指明自己的端口号
        ServerSocket serverSocket = new ServerSocket(8899);
        //调用accept()方法表示接受来自客户端的socket
        Socket socket = serverSocket.accept();
        //读入收入流的数据
        InputStream inputStream = socket.getInputStream();
        //不建议这么写(会导致数据丢失)
//        byte[] bytes = new byte[5];
//        int len;
//        while((len = inputStream.read(bytes)) != -1) {
    
    
//            String str = new String(bytes,0,len);
//            System.out.println(str);
//        }
        //建议这么写
        ByteArrayOutputStream byteArrayInputStream = new ByteArrayOutputStream();
        byte[] bytes = new byte[10];
        int len;
        while ((len = inputStream.read(bytes)) != -1){
    
    
            byteArrayInputStream.write(bytes,0,len);
        }
        System.out.println(byteArrayInputStream.toString());
        
        //关闭资源
        byteArrayInputStream.close();
        inputStream.close();
        socket.close();
        serverSocket.close();
    }

The server gives a feedback to the client after receiving the picture

 @Test
    public void client() throws IOException {
    
    

        //创建socket对象,指明服务器的ip和端口号
        InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
        Socket socket = new Socket(inetAddress,8899);

        //获取一个输出流,用于输出数据
        OutputStream outputStream = socket.getOutputStream();
        //写出数据
        File file = new File("三刀流索隆.jpg");

        FileInputStream fileInputStream = new FileInputStream(file);
        byte[] buffer = new byte[20];
        int len;
        while((len = fileInputStream.read(buffer))!= -1){
    
    
            outputStream.write(buffer,0,len);
        }
        //关闭数据的输出
        socket.shutdownOutput();

        //客户端发送完数据,等待服务端相应,把消息相应到控制台。
        InputStream inputStream = socket.getInputStream();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        while((len = inputStream.read(buffer)) != -1){
    
    
           byteArrayOutputStream.write(buffer,0,len);
        }
        System.out.println(byteArrayOutputStream.toString());
        //资源的关闭
        inputStream.close();
        byteArrayOutputStream.close();
        outputStream.close();
        socket.close();
    }

    @Test
    public void server() throws IOException {
    
    

        //创建serverSocket,指明自己的端口号
        ServerSocket serverSocket = new ServerSocket(8899);
        //调用accept()方法表示接受来自客户端的socket
        Socket socket = serverSocket.accept();
        //读入收入流的数据
        InputStream inputStream = socket.getInputStream();

        File file = new File("另一个三刀流索隆.jpg");
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        byte[] buffer = new byte[20];
        int len;
        while ((len = inputStream.read(buffer)) != -1){
    
    
            fileOutputStream.write(buffer,0,len);
        }
        System.out.println("服务器接受到图片");

        //服务端接受到数据之后给客户端一个反馈
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("服务端已经接受到来自客户端的数据!".getBytes());

        //关闭资源
        	fileOutputStream.close();
        	outputStream.close();
            inputStream.close();
            socket.close();
            serverSocket.close();
    }
  • The client needs to execute the following code after sending the data to tell the server that I have sent all the data.
    socket.shutdownOutput();
  • You need to start the server first, and then start the client. Because the TCP protocol is a communication protocol that requires a three-way handshake to establish a reliable connection.
  • Why is it three times, not once, not twice, or more times?
    The reason is that a reliable connection cannot be established once or twice, and no matter how many times, the improvement of the connection reliability is only minimal, but because of the establishment of the connection, too much resources are consumed.
    The TCP connection process can be analogized as:
    Client: I am Zhang San, who are you?
    Server: I know you are Zhang San, and I am Li Si.
    Client: I know you know that I am Zhang San and you are Li Si.
    In contrast, TCP protocol is to ensure data transmission as complete as possible, UDP is an unreliable connection method, but UDP protocol is not useless, such as network video transmission, to ensure the smoothness of the video as much as possible, occasionally Frame loss is acceptable, and the bombardment of general spam messages is also based on the UDP protocol.

The difference between webSocket and socket

https://www.cnblogs.com/Javi/p/9303020.html

Use of UDP-based Socket

    @Test
    public void client() throws IOException {
    
    
        DatagramSocket datagramSocket = new DatagramSocket();
        String str = "这是基于UPD协议发送的文字";
        byte[] data = str.getBytes();
        InetAddress localHost = InetAddress.getLocalHost();
        DatagramPacket datagramPacket = new DatagramPacket(data, 0, data.length, localHost, 9000);
        datagramSocket.send(datagramPacket);
        datagramSocket.close();
    }
    
    @Test
    public  void server() throws IOException {
    
    
        DatagramSocket datagramSocket = new DatagramSocket(9000);
        byte[] buffer = new byte[1024];
        DatagramPacket datagramPacket = new DatagramPacket(buffer,0,buffer.length);
        datagramSocket.receive(datagramPacket);
        System.out.println(new String(datagramPacket.getData(),0,datagramPacket.getLength()));
    }
  • Here you can start the client first and start the server, and no error will be reported, because UDP is a protocol that does not need to establish a reliable connection.

Guess you like

Origin blog.csdn.net/weixin_43941676/article/details/108434698