简体   繁体   English

服务器未从多个客户端(Java套接字)接收数据

[英]server doesn't receive data from multiple clients (java sockets)

I wrote a simple program where a server should print data sent by multiple clients. 我编写了一个简单的程序,其中服务器应打印多个客户端发送的数据。 But the server receives only partial data. 但是服务器仅接收部分数据。 Following are the relevant pieces of the code. 以下是代码的相关部分。

Server: 服务器:

try {
        serverSocket = new ServerSocket(8888);
    } catch (IOException e) {
        System.err.println("Could not listen on port: 8888");
        System.exit(-1);
    }
 while (listening) {
    Socket clientSocket = serverSocket.accept();
    BufferedReader reader = new BufferedReader(new InputStreamReader(
                            clientSocket.getInputStream()));
        System.out.println(reader.readLine());

        reader.close();
        clientSocket.close();
  }
  serverSocket.close();

Client: 客户:

  try {
        socket = new Socket("nimbus", 8888);
        writer = new PrintWriter(socket.getOutputStream(), true);
        localHost = InetAddress.getLocalHost();
    } 
    catch (UnknownHostException e) {} 
    catch (IOException e) {}

    StringBuilder msg1 = new StringBuilder("A: ");
    for(int i=1; i<=3; i++)
        msg1.append(i).append(' ');
    writer.println(localHost.getHostName() + " - " + msg1);

    StringBuilder msg2 = new StringBuilder("B: ");
    for(int i=4; i<=6; i++)
        msg2.append(i).append(' ');
    writer.println(localHost.getHostName() + " - " + msg2);

    StringBuilder msg3 = new StringBuilder("C: ");
    for(int i=7; i<=9; i++)
        msg3.append(i).append(' ');
    writer.println(localHost.getHostName() + " - " + msg3);

    writer.close();
    socket.close();

I get the following output (when run on 3 clients) 我得到以下输出(在3个客户端上运行时)

nimbus2 - A: 1 2 3 
nimbus3 - A: 1 2 3 
nimbus4 - A: 1 2 3

I don't get the second and third messages. 我没有收到第二和第三条消息。 Server keeps waiting. 服务器一直在等待。 Where am I going wrong? 我要去哪里错了?

Edit: In the server code, I tried removing reader.close() and clientSocket.close() . 编辑:在服务器代码中,我尝试删除reader.close()clientSocket.close() That didn't work either. 那也不起作用。 Another question -- if 3 clients send 3 messages, does it require 9 connections? 另一个问题-如果3个客户端发送3条消息,是否需要9个连接? (this is the reason, I closed the connection in the server code) (这是原因,我在服务器代码中关闭了连接)

You probably want to be delegating the handing of the socket to another thread. 您可能希望将套接字的处理委托给另一个线程。 I've written up an example that works by passing each incoming socket to an Executor so it can read all the inputs. 我编写了一个示例,该示例通过将每个传入的套接字传递给Executor来工作,以便它可以读取所有输入。 I use a Executors.newCachedThreadPool() which should grow to be as big as needed. 我使用了Executors.newCachedThreadPool(),它应该增长到需要的大小。 You could also use Executors.newFixedThreadPool(1) if you want it to only be able to handle 1 client at a time. 如果希望一次只能处理1个客户端,也可以使用Executors.newFixedThreadPool(1)。

The only other change I made was I removed the BufferedReader and replaced it with a Scanner. 我所做的唯一其他更改是我删除了BufferedReader,并用Scanner替换了它。 I was having issues with the BufferedReader not returning data. 我遇到了BufferedReader不能返回数据的问题。 I'm not sure why. 我不知道为什么。

Executor exe = Executors.newCachedThreadPool();
ServerSocket serverSocket = null;
try {
    serverSocket = new ServerSocket(8888);
} catch (IOException e) {
    System.err.println("Could not listen on port: 8888");
    System.exit(-1);
}
while (listening) {
    final Socket clientSocket = serverSocket.accept();

    exe.execute(new Runnable() {

        @Override
        public void run() {
            try {
                Scanner reader = new Scanner(clientSocket.getInputStream());
                while(reader.hasNextLine()){
                    String line = reader.nextLine();
                    System.out.println(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                clientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });

}
serverSocket.close();

It looks like you close the connection to the client before they can finish writing/before the server reads all of the messages they sent. 看起来您在客户端可以完成写入之前/在服务器读取他们发送的所有消息之前,已关闭与客户端的连接。 I think you need to continue to readline , and potentially not terminate the client's connection after they send you one message. 我认为您需要继续readline ,并且在他们向您发送一条消息之后,可能不终止客户端的连接。

John is right. 约翰是对的。 you close the client connection by calling clientsocket.close() after reading the message that is why you cannot get the other messages. 您在读取消息后通过调用clientsocket.close()关闭了客户端连接,这就是为什么您无法获得其他消息的原因。 you should call clientsocket.close() when you have received all the messages 收到所有消息后,应调用clientsocket.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM