簡體   English   中英

如何在Java中的多客戶端/服務器應用程序中查找所有已連接客戶端的IP地址?

[英]how to find ip address of all connected clients in multi-client/server application in java?

我用Java創建了一個簡單的多客戶端/服務器應用程序。 我想獲取所有已連接客戶端的列表。 如何獲取所有已連接客戶端的IP地址? 我在此創建簡單客戶端/服務器應用程序鏈接中引用並嘗試了代碼,以創建簡單應用程序

服務器代碼:

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

}

任何幫助將不勝感激。

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

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

至:

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

如果要保留已連接客戶端的列表,只需將socket.getRemoteSocketAddress()添加到ArrayList或最喜歡的任何數據結構。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM