简体   繁体   English

Java-套接字编程-如何使客户端从多个服务器接收消息?

[英]Java - Socket Programming - How can I make a client receive msg from multiple servers?

I need to have multiple client talk to multiple servers and process responses from them. 我需要让多个客户端与多个服务器对话并处理它们的响应。

So far, I have been able to write the server code which binds to multiple clients (spawns a thread for each client) and client connect to multiple servers. 到目前为止,我已经能够编写绑定到多个客户端的服务器代码(为每个客户端生成一个线程),并且客户端连接到多个服务器。

The place where I facing problem is on the client side - I am not able to receive responses from the servers. 我遇到问题的地方是客户端-我无法从服务器接收响应。

The sequence of operations are as below - 操作顺序如下-

Suppose I have 2 servers and 1 client. 假设我有2台服务器和1个客户端。 client connects to both servers, sends them messages, both servers receive it and both send a reply to the client - I am not able to receive this reply. 客户端连接到两台服务器,向它们发送消息,两台服务器都接收到该消息,并且都向客户端发送回复-我无法收到此回复。

Server Code - 服务器代码-

 @Override
  public void run() {
    try {

      // create a serversocket to listen to requests
      ServerSocket serverSocket = new ServerSocket(port);

      // create n sockets to listen to 5 client
      for (int i = 0; i < n; i++) {
        Socket socket = serverSocket.accept();
        // create a processor thread for each to read and process the incoming Messages
        Processor processor = new Processor(socket);
        processor.start();
      }

     serverSocket.close();
    } catch (IOException e) {
      e.printStackTrace();
    }

Processor at server code - 服务器代码处的处理器-

@Override
  public void run() {
    try {
      ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
      OutputStreamWriter out = new OutputStreamWriter(socket.getOutputStream());

      while (true) {
        String str = in.readObject();

        System.out.println(message);

        out.write("Got your message " + message.toString());

      }
    } catch (IOException e) {
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    } catch (ClassCastException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    }

    System.out.println("Processor completed " );
  }

Client code - 客户代码-

public static void main(String[] args) throws IOException, InterruptedException {

    // make the connections with other nodes
    connections = connect();

    // connect() creates connections from the client to all servers and stores the socket and out objects in the object called Connections.Code omitted to avoid clutter

    // process all the commands 
    while(!commands.isEmpty()){

      for(int i=0 ; i<2; i++){
      send(commands.poll() , i);

    }

      Thread.sleep(500);
    }

  }


  // Sends Message m to the node i
  public static synchronized void send(Message m, int i) {
    try {
      connections.outs[i].writeInt(m.nodeId);
      connections.outs[i].writeInt(m.timestamp);
      connections.outs[i].writeObject(m.type);
      connections.outs[i].writeObject(m.value);
      connections.outs[i].flush();

      InputStreamReader isr = new       InputStreamReader(connections.sockets[i].getInputStream());
      final BufferedReader br = new BufferedReader(isr);

      new Thread() {
        public void run() {
          try {
            while (true) {
              String message = br.readLine();
              System.out.println("Message received from the server : " +message);
            }
          } catch(IOException e) {
            e.printStackTrace();
          }
        }
      }.start();

    } catch (IOException e) {
      e.printStackTrace();
    }
  }

I am sure I am doing something wrong when listening to the message. 我确定在收听消息时我做错了什么。 Any suggestion no how to receive and process messages from multiple servers would be very helpful. 关于如何从多个服务器接收和处理消息的任何建议都将非常有帮助。

TIA TIA

I am facing two problems: 我面临两个问题:

1. You did not flush. 1.您没有冲洗。

out.write("Got your message " + message.toString()); out.write(“收到您的消息” + message.toString());

2. In the server you send no \\n 2.在服务器中,您不发送\\ n

The problem is the method readLine 问题是方法readLine

  new Thread() {
    public void run() {
      try {
        while (true) {
          String message = br.readLine();
          System.out.println("Message received from the server : " +message);
        }
      } catch(IOException e) {
        e.printStackTrace();
      }
    }
  }.start();

from Documentation : 来自文档

Reads a line of text. 读取一行文本。 A line is considered to be terminated by any one of a line feed ('\\n'), a carriage return ('\\r'), or a carriage return followed immediately by a linefeed. 一行被认为由换行符('\\ n'),回车符('\\ r')或回车符后紧跟换行符之一终止。

But the Server neither send a \\n nor a \\r. 但是服务器既不发送\\ n也不发送\\ r。 Try 尝试

  out.write("Got your message " + message.toString() + "\n");

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

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