📜  在Java中使用 UDP 数据报套接字(1)

📅  最后修改于: 2023-12-03 14:51:17.096000             🧑  作者: Mango

在Java中使用UDP数据报套接字

UDP(User Datagram Protocol)是一种面向无连接的协议,它将数据发送到网络的传输层,以无连接的方式将数据包发到目标计算机。与TCP不同,它不保证数据的传输可靠性,也不保证数据包到达目的地的顺序与发送的顺序一致。

在Java中使用UDP数据报套接字,可以使用Java提供的java.net包中的DatagramSocket和DatagramPacket类实现。下面是一个简单的示例代码:

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 = new byte[1024];

        while(true) {
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
            serverSocket.receive(receivePacket);

            String sentence = new String(receivePacket.getData(), 0, receivePacket.getLength());
            System.out.println("Received: " + sentence);

            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);
        }
    }
}

此示例程序创建了一个DatagramSocket对象,该对象使用参数9876指定了端口号来监听来自网络的UDP数据报。程序将从客户端接收到的数据报转换为大写,并将转换后的数据报发送回客户端。

以下是客户端代码的示例:

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 = new byte[1024];
        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();
    }
}

此示例程序创建了一个DatagramSocket对象,并向服务器发送UDP数据报(使用SocketAddress指定目标地址和端口号)。程序将从服务器接收到的响应转换为字符串,并打印在控制台上。

以上是UDP数据报套接字的简单示例,您可以根据需要进行调整及扩展。