[英]how to find ip address of all connected clients in multi-client/server application in java?
i have created a simple multi-client/server app in java. 我用Java创建了一个简单的多客户端/服务器应用程序。 and i want to get the list of all connected clients. 我想获取所有已连接客户端的列表。 how can i get the ip address of all connected clients? 如何获取所有已连接客户端的IP地址? i referred and tried code on this creating simple client/server app link for creating simple app 我在此创建简单客户端/服务器应用程序链接中引用并尝试了代码,以创建简单应用程序
server Code: 服务器代码:
public class ChatServer implements Runnable
{
private ServerSocket server = null;
private Thread thread = null;
private ChatServerThread client = null;
public ChatServer(int port)
{ try
{ System.out.println("Binding to port " + port + ", please wait ...");
server = new ServerSocket(port);
System.out.println("Server started: " + server);
start();
}
catch(IOException ioe)
{ System.out.println(ioe); }
}
public void run()
{ while (thread != null)
{ try
{ System.out.println("Waiting for a client ...");
addThread(server.accept());
}
catch(IOException ie)
{ System.out.println("Acceptance Error: " + ie); }
}
}
public void addThread(Socket socket)
{ System.out.println("Client accepted: " + socket);
client = new ChatServerThread(this, socket);
try
{ client.open();
client.start();
}
catch(IOException ioe)
{ System.out.println("Error opening thread: " + ioe); }
}
public void start()
public void stop()
public static void main(String args[])
} }
any help will be appreciated. 任何帮助将不胜感激。
If you only want to print the addresses out, simply change: 如果只想打印地址,只需更改:
System.out.println("Client accepted: " + socket);
To: 至:
System.out.println("Client accepted: " + socket.getRemoteSocketAddress().toString());
If you want to keep a list of connected clients, simply add socket.getRemoteSocketAddress()
to an ArrayList
, or whatever data structure you like the most. 如果要保留已连接客户端的列表,只需将socket.getRemoteSocketAddress()
添加到ArrayList
或最喜欢的任何数据结构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.