Table of contents
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.
step:
1. Import the necessary libraries
First, we need to import the network programming library provided by Java, including java.net
and 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 DatagramSocket
do 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:
-
DatagramSocket
Class: 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.
-
DatagramPacket
Class: 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.
-
String
Class: 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:
-
BufferedReader
Class: 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.
-
InputStreamReader
Class: 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.
-
DatagramSocket
For descriptions of classes andDatagramPacket
classes, 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 DatagramSocket
and DatagramPacket
classes to handle UDP sending and receiving. In the client code, we use BufferedReader
the and InputStreamReader
class to read user input, and the DatagramSocket
and DatagramPacket
class 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.