一台服务器上的多个客户端java

时间:2013-01-30 23:25:35

标签: java

好的,所以我的一个朋友在教我网络上的东西,我们有一个成功的程序。这是一个简单的聊天,我们用putty连接,但我们有一个问题。一次只能连接一个客户端。有人可以说一次如何连接更多客户端以及如何限制连接的客户端数量?

public class Base 
{
  static ServerSocket serverSocket;
  public static void main(String[] args) throws IOException
  {
    final ServerSocket serverSocket = new ServerSocket (1337);
    Thread thread = new Thread(new Runnable()
                                 {
      public void run()
      {
        try
        {
          System.out.println("Waiting for connections...");
          //Make Socket on port
          Socket client = serverSocket.accept();
          System.out.println("Connection from " + client.getInetAddress());
          //initialixe no socket with connect server gets
          BufferedReader in = new BufferedReader (new InputStreamReader(client.getInputStream()));
          //init new beffer to read incom
          //while loop to read stuff
          final BufferedWriter out = new BufferedWriter(new PrintWriter(client.getOutputStream()));
          out.write("Your Connected Mate");
          out.newLine();
          out.flush();
          new Thread(new Runnable()
                       {
            public void run()
            {
              try
              {
                Scanner s = new Scanner(System.in);
                while(s.hasNext())
                {
                  out.write("CLIENT] " + s.nextLine());
                  out.newLine();
                  out.flush();
                }
              }
              catch(Exception e)
              {
                e.printStackTrace();
              }
            }
          }).start();
          while(true)
          {
            //make a string form anything thats read from the socket
            String tmp = in.readLine();
            //if the string isnt null (which it is if we disconnect) print it out
            if(tmp != null)
            {
              System.out.println("[CLIENT -> SERVER] " + tmp);
            }
          }
        }
        catch(Exception e)
        {
          e.printStackTrace();
        }
      }
    });
    thread.run();
  }
}

我们没有尝试任何事情,因为我们不知道:)

2 个答案:

答案 0 :(得分:0)

我认为您需要在接受客户端中的连接(在现有while(true)线程内)放置while(notInterrupted)循环(或run或其他内容)。如果你要让连接保持活动很长时间,我想你会想要生成处理它们的线程(简单的web服务器等用例可能不需要生成线程 - 时间量每个客户端占用的数量可能少于产生线程所花费的数量。

尝试寻找一些示例服务器,看看是否可以根据需要调整它们。

至于限制能够连接的客户端的数量,您可能需要某种处理线程池的阻塞数据结构,并且只有在释放一个时才提供一个。想到Thread Pool ......

答案 1 :(得分:0)

在while循环的第一个try语句中包围所有内容,只要您希望连接另一个客户端,它就会一直重复。然后,您需要将输入代码(如in.readLine()代码)放入其自己的Thread中,就像您为Server的输出所做的那样(out.write())

每个客户端都需要自己的输入线程和输出线程。尝试将客户端和服务器之间的通信保持在主线程之外,以便服务器可以继续接受连接。

示例代码:

//Setup your ServerSocket

ServerSocket server = new ServerSocket();

while (true){
    Socket s = server.accept();
    Thread input = new Thread(new Runnable(){
            //Set up your BufferedReader or whatever input method you are using here
                      BufferedReader in = new BufferedReader (new InputStreamReader(client.getInputStream()));

            while(true)
            {
            //make a string form anything thats read from the socket
            String tmp = in.readLine();
            //if the string isnt null (which it is if we disconnect) print it out
            if(tmp != null)
            {
              System.out.println("[CLIENT -> SERVER] " + tmp);
            }
          }
        }).start();

    //Do the same for your output as you just did for your input (make a new thread, make a new writer object, etc.)
}
}

注意:这是非常粗略的例子。你需要填写一些空白,也许一些{} 希望这有帮助!

相关问题