【问题标题】:Communicating with multiple clients - Java Server与多个客户端通信 - Java Server
【发布时间】:2013-02-14 19:27:12
【问题描述】:

我实现了一个小型 Java 聊天室程序,客户端可以在其中与服务器通信。尽管多个客户端不起作用-我相信这是因为客户端在连接时保留了一个套接字?有没有一种简单的方法来添加多个客户端功能?感谢您的帮助。

public void startRunning(){
      try{
         server = new ServerSocket(6789, 100); // port no, max users
         while(true){
            try{
               waitForConnection();
               setupStreams();
               connectionRecieving();
            }catch(EOFException eofException){
               showMessage("Server ended connection \n");
            }finally{
               closeConnection();
            }
         }
      }catch(IOException ioException){
         ioException.printStackTrace();
      }
   }

   // Wait for connection
   private void waitForConnection() throws IOException{
      showMessage("Attempting connection... \n");
      connection = server.accept();
      showMessage("Connected to: " + connection.getInetAddress().getHostName() + "\n");
   }

   // Get stream to send and receive data
   private void setupStreams() throws IOException{
      output = new ObjectOutputStream(connection.getOutputStream());
      output.flush();
      input = new ObjectInputStream(connection.getInputStream());
   }

   // Close streams and sockets 
   private void closeConnection(){
      showMessage("----- \nClosing connections... \n");
      try{
         output.close();
         input.close();
         connection.close();
      }catch(IOException ioException){
         ioException.printStackTrace();
      }
   }

【问题讨论】:

  • 问题是每个连接都会覆盖前一个。您需要有多个连接字段和多个输入/输出流。确实,您需要生成一个线程来处理连接,并且 可以维护连接和流。
  • docs.oracle.com/javase/tutorial/networking/sockets/… - 请参阅本教程的最后一节,它有一个完整的工作示例,说明如何支持多个客户端。

标签: java multithreading sockets objectoutputstream objectinputstream


【解决方案1】:

要同时读取和写入多个客户端,您需要单独的线程(阻塞 IO),或者如果您想使用单个线程,则需要 NIO(非阻塞 IO)。

您可以查看this post 了解实现差异,但 NIO 通常是更有效的方法。

使用阻塞 I/O 通常遵循您上面使用的代码,除了您需要一个单独的线程来处理每个接受的套接字。使用 NIO,使用起来稍微复杂一些;查看this tutorial

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-21
    • 2021-06-18
    相关资源
    最近更新 更多