如何在java中找到多客户端/服务器应用程序中所有连接客户端的IP地址?

时间:2013-12-04 05:12:34

标签: java

我在java中创建了一个简单的多客户端/服务器应用程序。 我想获得所有连接客户的列表。 我怎样才能获得所有连接客户端的IP地址? 我提到并尝试了creating simple client/server app的代码 用于创建简单应用的链接

服务器代码:

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[])

}

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

如果您只想打印地址,只需更改:

System.out.println("Client accepted: " + socket);

要:

System.out.println("Client accepted: " + socket.getRemoteSocketAddress().toString());

如果您想保留已连接客户的列表,只需将socket.getRemoteSocketAddress()添加到ArrayList或您最喜欢的任何数据结构。