服务器未检测到第二个客户端正在连接

bbmckpt7  于 2021-07-05  发布在  Java
关注(0)|答案(1)|浏览(297)

我遇到的问题是,当我打开第二个客户机时,服务器似乎没有检测到第二个客户机已打开。第一次打开客户机时,它工作正常,服务器检测到客户机已连接。
服务器:

public class Server {

Socket previousSocket = null;

private static int port = 9001;

public static void main(String[] args) throws Exception {
    ServerSocket serverSocket = new ServerSocket(port);
    System.out.println("[SERVER] Server successfully launched on port: " + port);

    DatagramSocket UDPSocket = new DatagramSocket(9002);

    Socket previousSocket = null;
    while (true) {
        Socket newSocket = serverSocket.accept();

       System.out.println("new client connected");

        if (previousSocket == null) { 
            previousSocket = newSocket;

            System.out.println("1 st client");

        } else {
            System.out.println("2 nd client");
            previousSocket = null;
        }

        byte[] data = new byte[500];
        DatagramPacket received = new DatagramPacket(data, data.length);

        while(true) {
            UDPSocket.receive(received);

            String receivedData = new String(received.getData());

            System.out.println(receivedData);
        }
    }
}
}

客户:

public ChatClient() throws UnknownHostException, IOException {

    Socket socket = new Socket("127.0.0.1", 9001);

    Scanner scanner = new Scanner(System.in);

    DatagramSocket UDPSocket = new DatagramSocket();

    while(scanner.hasNextLine()) {
        String message = scanner.nextLine();
        InetAddress ip = InetAddress.getByName("127.0.0.1");

        DatagramPacket packet = new DatagramPacket(message.getBytes(), message.getBytes().length, ip, 9002);
        UDPSocket.send(packet);
    }
}
jmo0nnb3

jmo0nnb31#

下面的循环永远不会结束,这就是问题的原因

while(true) {
            UDPSocket.receive(received);

            String receivedData = new String(received.getData());

            System.out.println(receivedData);
        }

相关问题