server不向hashmap添加地址和端口

pvabu6sv  于 2021-07-04  发布在  Java
关注(0)|答案(0)|浏览(221)

我有一个程序,将每个连接到udp服务器的客户端的inetaddress和端口放在hashmap中。这样做的原因是,我可以从客户端接收消息,然后将它们发送到服务器,并将它们发送到hashmap中的其他客户端。
但是当我这样做的时候,它只在hashmap中放一次。我怎么能让每一个新客户 HashMap<InetAdress, Integer> 对于每个新的客户端连接?
服务器:

private static int port = 9001;
private static HashMap<InetAddress, Integer> clients = new HashMap<InetAddress, Integer>();

public static void main(String[] args) throws Exception {

    DatagramSocket UDPSocket = new DatagramSocket(9002);
    System.out.println("[SERVER] UDP Server successfully launched on port: " + port);

    byte[] data = new byte[1000];
    DatagramPacket receivePacket = new DatagramPacket(data, data.length);

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

            while(true) {
                InetAddress ip = receivePacket.getAddress();
                int port = receivePacket.getPort();

                clients.put(ip, port);
            }
    }

}

客户:

public ChatClient() throws UnknownHostException, IOException {

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

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题