Java uses UDP and TCP for network communication

UDP

Tool class

public class UDP {
    private static final int port = 9000;  //Port number to use

    /**
     * send message
     * @Param ip ip of the other party, String
     * @Param msg Message to send, String type
     */
    public static void send(String ip,String msg) throws IOException {
        //Opposite party ip,Can't be used directly String,Need to change
        InetAddress ipAddr = InetAddress.getByName(ip);

        //socket,Equivalent to wharf
        DatagramSocket socket = new DatagramSocket();

        // packet,Data package, equivalent to container
        // Parameters: byte[],Data length, opposite party ip(Cannot write directly String),Port number to use
        // Any type can be transferred, such as file transfer, not limited to String,Because they all need to be converted into byte arrays
        DatagramPacket packet = new DatagramPacket(msg.getBytes(), msg.length(),ipAddr,port);

        //adopt socket Send out packet
        socket.send(packet);
        System.out.println("send: "+msg);

        //Close socket
        socket.close();
    }


    /**
     *Listening port, receiving messages
     */
    public static void receive() throws IOException {
        //socket,Specifies the port to listen on. Send and receive the same port
        DatagramSocket socket = new DatagramSocket(port);

        // packet,Use one byte[]To store data
        // The first value is the length of byte array, and the second value is the number of bytes to be read. Put the read data into byte[]in
        // The number of bytes read should be less than or equal to byte[]The length of, or it won't fit
        DatagramPacket packet = new DatagramPacket(new byte[1024], 1024);

        //Monitor all the time
        while (true){
            socket.receive(packet); //adopt socket Receive packet,use packet To encapsulate the received data. If no data is received, it will block all the time
            byte[] data = packet.getData(); //Obtain packet Data in (entire byte[])
            int length = packet.getLength(); //Gets the actual length of the data. packet Medium byte[]Not necessarily full, need to get the actual number of bytes

            String msg = new String(data, 0, length); //byte[],offset,length
            // msg = new String(data); //In fact, it's OK not to get the actual length
            System.out.println("received: "+msg);

            //Get this machine ip,Sender ip
            // InetAddress localAddress = socket.getLocalAddress(); //This machine
            // InetAddress address = packet.getAddress();  //Sender
            // String ip = address.getHostAddress(); //String Type ip

            // socket.close();  //Close socket
            //Keep listening, don't turn off socket
            // When exiting a chat, such as exiting a desktop program or web Click "end chat" for the project, no interaction for more than 2 minutes, need to close socket

        }
    }

}

UDP does not distinguish between client and server. The sockets used on both sides are datagram sockets and the packets used are datagram packets. Send and receive can use the same socket.

 

 

send message

public class Send {
    public static void main(String[] args) throws IOException {
        UDP.send("127.0.0.1", "hello");
    }
}

 

 

receive messages

public class Receive {
    public static void main(String[] args) throws IOException {
        UDP.receive();
    }
}

 

 

Start the receiver first, then the sender.

 

There is a problem: write two main classes and start them respectively. Generally, do not do this. Use multi-threaded instead.

 

Test class

public class Test {
    public static void main(String[] args) throws IOException, InterruptedException {
        //Start a thread, listen to the port and receive messages
        Thread receiveThread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    UDP.receive();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        receiveThread.start();

        //For fear that the receiving thread is not allocated to the time slice temporarily, it will execute after sending the message. If it fails to receive the message in front of it, it can make the sending thread sleep for a while
        Thread.sleep(100);

        //You can also turn on a single thread to send messages
        UDP.send("127.0.0.1","hello");
    }
}

 

UDP is unreliable. No matter whether the ip memory of the other party does not exist or whether the other party starts monitoring, it can be sent directly, no matter whether the other party can receive it or not.

 

 

 

 

 

 

TCP

Tool class

public class TCP {
    private static final int port = 9000;  //Port number to use

    /**
     * send message
     * @Param ip ip of the other party, String
     * @Param msg Message to send, String type
     */
    public static void send(String ip,String msg) throws IOException {
        //Client side socket. Direct use String Type of opposite party's ip
        Socket socket = new Socket(ip, port);

        //Send data to server
        OutputStream os = socket.getOutputStream(); //Output stream
        os.write(msg.getBytes()); //byte[]
        System.out.println("send: "+msg);
    }


    /**
     *Listening port, receiving messages
     */
    public static void receive() throws IOException {
        //Server side socket,Specify the port to listen on
        ServerSocket serverSocket = new ServerSocket(port);

        //Monitor all the time
        while (true) {
            //Receive the client's request and create a corresponding Socket To communicate with the client
            Socket socket = serverSocket.accept();

            //Receive data sent by client
            InputStream is = socket.getInputStream();
            byte[] buff = new byte[1024];
            int length = is.read(buff); //Read data to byte[]Returns the number of bytes read to
            java.lang.String msg = new java.lang.String(buff, 0, length); //There are many. String Class, don't misdirect
            System.out.println("received: " + msg);

            // Get this machine ip,Sender ip
            // InetAddress localAddress = socket.getLocalAddress();  //This machine
            // InetAddress inetAddress = socket.getInetAddress();  //Sender// String ipAddress = localAddress.getHostAddress(); //Obtain String Type IP

            // socket.close();
            
        }
    }

}

TCP should distinguish between client and server. Socket is used for client and ServerSocket is used for server. Socket corresponding to client is obtained through ServerSocket to communicate with client.

The client and the server are relative. The sending party is called the client, and the receiving party is called the server. Generally, the client and the server are required.

After receiving the other party's message, you can call send() to pass in the other party's ip to communicate with it, or you can write an overloaded send() to pass in the socket corresponding to the client.

 

 

Test class

public class Test {
    
    public static void main(String[] args) throws IOException, InterruptedException {
        //Start a thread to listen to the port and receive messages
        Thread receiveThread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    TCP.receive();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        receiveThread.start();

        //For fear that the receiving thread is not allocated to the time slice temporarily, it will execute after sending the message. If it fails to receive the message in front of it, it can make the sending thread sleep for a while
        Thread.sleep(100);

        //You can also turn on a single thread to send messages
        TCP.send("127.0.0.1","hello");
    }
    
}

 

TCP is reliable, three handshakes confirm that both sides can communicate normally.

Tags: Java socket less

Posted on Tue, 24 Mar 2020 07:40:46 -0700 by ephmynus