Using the Java server to realize the sending and receiving of UDP messages (multithreading)

Introduction:

In this blog, we will introduce how to use the Java server to send and receive UDP messages, and handle concurrent requests through multithreading. UDP (User Datagram Protocol) is a connectionless and unreliable transmission protocol, which is suitable for application scenarios with high real-time requirements, such as real-time games and voice communication.
insert image description here

step:

1. Import the necessary libraries

First, we need to import the network programming library provided by Java, including java.netand java.io.

2. Create server-side code

On the server side, we need to create a Socket object and bind it to the specified port. Then, create an infinite loop in which the client's request is received and processed accordingly. Since UDP is connectionless, we can DatagramSocketdo it through classes.

3. Create client code

On the client side, we also need to create a Socket object and specify the IP address and port number of the server. Then, send and receive UDP datagrams through the Socket object.

4. Implement multithreading

If we want the server to be able to handle requests from multiple clients, we can use multithreading to achieve concurrent processing. Whenever a new request arrives at the server, a new thread is created to handle the request.

5. Test run

After both the server and client code are complete, we can run them separately and watch the console output. Make sure that the server can receive the message sent by the client and process it correctly.

Sample code:

The following is a simple Java code example that demonstrates how to implement UDP message sending and receiving (multi-threaded):

// 服务器端代码
import java.io.*;
import java.net.*;

public class UDPServer {
    
    
   public static void main(String args[]) throws Exception {
    
    
      DatagramSocket serverSocket = new DatagramSocket(9876);
      byte[] receiveData = new byte[1024];
      byte[] sendData;
      
      while (true) {
    
    
         DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
         serverSocket.receive(receivePacket);
         
         String sentence = new String(receivePacket.getData());
         InetAddress IPAddress = receivePacket.getAddress();
         int port = receivePacket.getPort();
         
         String capitalizedSentence = sentence.toUpperCase();
         sendData = capitalizedSentence.getBytes();
         
         DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
         serverSocket.send(sendPacket);
      }
   }
}

// 客户端代码
import java.io.*;
import java.net.*;

public class UDPClient {
    
    
   public static void main(String args[]) throws Exception {
    
    
      BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
      DatagramSocket clientSocket = new DatagramSocket();
      InetAddress IPAddress = InetAddress.getByName("localhost");
      byte[] sendData;
      byte[] receiveData = new byte[1024];
      
      String sentence = inFromUser.readLine();
      sendData = sentence.getBytes();
      
      DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
      clientSocket.send(sendPacket);
      
      DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
      clientSocket.receive(receivePacket);
      
      String modifiedSentence = new String(receivePacket.getData());
      System.out.println("FROM SERVER:" + modifiedSentence);
      
      clientSocket.close();
   }
}

function description

Of course, here is a more detailed description of the class and function interface:

Server-side code description:

  1. DatagramSocketClass: Represents a socket for sending and receiving UDP datagrams. It has the following common methods:

    • DatagramSocket(int port): Create a DatagramSocket object bound to the specified port.
    • void receive(DatagramPacket p): Store the received UDP datagram in the given DatagramPacket object.
    • void send(DatagramPacket p): Sends a UDP datagram in the given DatagramPacket object.
  2. DatagramPacketClass: Represents a UDP datagram. It has the following common methods:

    • DatagramPacket(byte[] buf, int length): Create a DatagramPacket object with a specified length for receiving data.
    • DatagramPacket(byte[] buf, int length, InetAddress address, int port): Create a DatagramPacket object with a specified length, which is used to send data to the specified IP address and port number.
    • byte[] getData(): Returns the received or sent data.
    • InetAddress getAddress(): Returns the IP address of the remote host.
    • int getPort(): Returns the port number of the remote host.
  3. StringClass: Represents a string object. It has the following common methods:

    • String(byte[] bytes): Creates a new string object using the specified byte array.
    • String(byte[] bytes, int offset, int length): Creates a new string object using a portion of the specified byte array.
    • byte[] getBytes(): Converts a string to a byte array.

Client code description:

  1. BufferedReaderClass: A buffer for reading text data from an input stream. It has the following common methods:

    • BufferedReader(Reader reader): Create a new buffered reader.
    • String readLine(): Read a line of text and return it.
  2. InputStreamReaderClass: A bridge that converts byte streams to character streams. It has the following common constructors:

    • InputStreamReader(InputStream in): Creates an input stream reader that converts a byte stream to a character stream.
  3. DatagramSocketFor descriptions of classes and DatagramPacketclasses, please refer to the explanation in the server-side code.

I hope these detailed class and function interface descriptions can help you better understand and apply the implementation process of sending and receiving UDP messages (multithreading). If you have any questions, please feel free to ask.

Summarize:

In the server-side code, we use DatagramSocketand DatagramPacketclasses to handle UDP sending and receiving. In the client code, we use BufferedReaderthe and InputStreamReaderclass to read user input, and the DatagramSocketand DatagramPacketclass to send and receive UDP datagrams.

Through this blog, we learned how to use the Java server to send and receive UDP messages, and handle concurrent requests in a multi-threaded manner. This is very useful for application scenarios with high real-time requirements, such as game development, voice communication, etc. Hope this article can help you understand and apply UDP network programming. If you have any questions, please feel free to leave a message.

Guess you like

Origin blog.csdn.net/lzyzuixin/article/details/132331271