问题描述
我有一个程序,其中将连接到UDP服务器的每个客户端的inetAddress和端口放在哈希图中。这样做的原因是这样,我可以将来自客户端的消息发送给服务器,然后将其发送给哈希图中的其他客户端。
但是,当我这样做时,它仅将其放入哈希表一次。我如何才能为每个新客户端为每个新客户端连接添加一个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);
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)