当我们从 UDP 服务器接收数据包时,为什么我们必须在单独的线程中接收它们?

When we receive packets from an UDP server, why do we have to receive them in a seperate thread?

所以我的申请很简单。如果您通过扫描仪输入内容,它会将其发送到服务器,服务器将其发送回客户端。但是,我不明白为什么我们必须把我们处理从服务器接收数据包的代码放到一个线程中?

下面的代码工作正常,但如果我不使用多线程,那么应用程序将无法工作。我发送数据包的部分也停止工作。你能解释一下为什么会这样吗?

public class Client {

private static DatagramSocket socket = null;

public static void main(String[] args) {

    System.out.println("Send to server:");

    Scanner scanner = new Scanner(System.in);

    while (true) {

        try {
            // port shoudn't be the same as in TCP but the port in the datagram packet must
            // be the same!
            socket = new DatagramSocket();
        } catch (SocketException e1) {
            System.out.println("[CLIENT] Unable to initiate DatagramSocket");
        }

        InetAddress ip = null;

        try {
            ip = InetAddress.getByName("127.0.0.1");
        } catch (UnknownHostException e) {
            System.out.println("[CLIENT] Unable to determine server IP");
        }

        // must be in a while loop so we can continuously send messages to server
        String message = null;

        Thread thread = new Thread(new Runnable() {
            
            @Override
            public void run() {
                // TODO Auto-generated method stub
                receive();
            }
        });
        thread.start();
        
        while (scanner.hasNextLine()) {
            message = scanner.nextLine();

            byte[] buffer = message.getBytes();

            DatagramPacket packet = new DatagramPacket(buffer, buffer.length, ip, 6066);

            try {
                socket.send(packet);
            } catch (IOException e) {
                System.out.println("[CLIENT] Unable to send packet to server");
            }
        }

    }

}

private static void receive() {
    
    // receiving from server

    byte[] buffer2 = new byte[100];

    DatagramPacket ps = new DatagramPacket(buffer2, buffer2.length);

    while (true) {
        try {
            socket.receive(ps);
        } catch (IOException e) {
            System.out.println("[CLIENT] Unable to receive packets from server.");
        }

        System.out.println("[SERVER] " + new String(ps.getData()));

    }
}

}

If you type something through the scanner it sends it over to the server, the server sends it back to client.

所以 main 方法在主线程上运行并完成一些工作。您刚刚提到的职位。

阅读一些用户输入加上以下部分

 while (scanner.hasNextLine()) {
            message = scanner.nextLine();

            byte[] buffer = message.getBytes();

            DatagramPacket packet = new DatagramPacket(buffer, buffer.length, ip, 6066);

            try {
                socket.send(packet);
            } catch (IOException e) {
                System.out.println("[CLIENT] Unable to send packet to server");
            }
        }

Title: receive packets from an UDP server

您想接收数据包,但又不想阻止用户输入某些内容并将其发送到服务器。

因此你需要同时做两份工作。又名多线程