Java UDP服务器和客户端源码 -javarevisited


Java中的DatagramPacket和DatagramSocket类支持在应用程序级别利用UDP套接字通信。让我们用Java编写一个简单的服务器和一个客户端,它们使用UDP套接字通信相互通信。
在此示例中,套接字服务器String从客户端接收类型的数据,并将大写的字符串发送回客户端。

public class UDPServer{
  // Server UDP socket runs at this port
  public final static int SERVICE_PORT=50001;
 
  public static void main(String[] args) throws IOException{
    try{
     
// Instantiate a new DatagramSocket to receive responses from the client
      DatagramSocket serverSocket = new DatagramSocket(SERVICE_PORT);
      
     
/* Create buffers to hold sending and receiving data.
      It temporarily stores data in case of communication delays */

      byte[] receivingDataBuffer = new byte[1024];
      byte[] sendingDataBuffer = new byte[1024];
      
     
/* Instantiate a UDP packet to store the 
      client data using the buffer for receiving data*/

      DatagramPacket inputPacket = new DatagramPacket(receivingDataBuffer, receivingDataBuffer.length);
      System.out.println(
"Waiting for a client to connect...");
      
     
// Receive data from the client and store in inputPacket
      serverSocket.receive(inputPacket);
      
     
// Printing out the client sent data
      String receivedData = new String(inputPacket.getData());
      System.out.println(
"Sent from the client: "+receivedData);
      
     
/* 
      * Convert client sent data string to upper case,
      * Convert it to bytes
      *  and store it in the corresponding buffer. */

      sendingDataBuffer = receivedData.toUpperCase().getBytes();
      
     
// Obtain client's IP address and the port
      InetAddress senderAddress = inputPacket.getAddress();
      int senderPort = inputPacket.getPort();
      
     
// Create new UDP packet with data to send to the client
      DatagramPacket outputPacket = new DatagramPacket(
        sendingDataBuffer, sendingDataBuffer.length,
        senderAddress,senderPort
      );
      
     
// Send the created packet to client
      serverSocket.send(outputPacket);
     
// Close the socket connection
      serverSocket.close();
    }
    catch (SocketException e){
      e.printStackTrace();
    }
  }
}

客户端:

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class UDPClient{
  /* The server port to which 
  the client socket is going to connect */

  public final static int SERVICE_PORT = 50001;
  
  public static void main(String[] args) throws IOException{
    try{
     
/* Instantiate client socket. 
      No need to bind to a specific port */

      DatagramSocket clientSocket = new DatagramSocket();
      
     
// Get the IP address of the server
      InetAddress IPAddress = InetAddress.getByName(
"localhost");
      
     
// Creating corresponding buffers
      byte[] sendingDataBuffer = new byte[1024];
      byte[] receivingDataBuffer = new byte[1024];
      
     
/* Converting data to bytes and 
      storing them in the sending buffer */

      String sentence =
"Hello from UDP client";
      sendingDataBuffer = sentence.getBytes();
      
     
// Creating a UDP packet 
      DatagramPacket sendingPacket = new DatagramPacket(sendingDataBuffer,sendingDataBuffer.length,IPAddress, SERVICE_PORT);
      
     
// sending UDP packet to the server
      clientSocket.send(sendingPacket);
      
     
// Get the server response .i.e. capitalized sentence
      DatagramPacket receivingPacket = new DatagramPacket(receivingDataBuffer,receivingDataBuffer.length);
      clientSocket.receive(receivingPacket);
      
     
// Printing the received data
      String receivedData = new String(receivingPacket.getData());
      System.out.println(
"Sent from the server: "+receivedData);
      
     
// Closing the socket connection with the server
      clientSocket.close();
    }
    catch(SocketException e) {
      e.printStackTrace();
    }
  }
}

运行,在服务器端看到:
Waiting for a client to connect...
Sent from the client: Hello from UDP client

客户端看到:

sent from the server: HELLO FROM UDP CLIENT