【问题标题】:Java - Socket Programming - How can I make a client receive msg from multiple servers?Java - 套接字编程 - 如何让客户端从多个服务器接收消息?
【发布时间】:2017-03-25 07:22:10
【问题描述】:

我需要让多个客户端与多个服务器通信并处理来自它们的响应。

到目前为止,我已经能够编写绑定到多个客户端的服务器代码(为每个客户端生成一个线程)并且客户端连接到多个服务器。

我遇到问题的地方在客户端 - 我无法接收来自服务器的响应。

操作顺序如下-

假设我有 2 个服务器和 1 个客户端。客户端连接到两台服务器,向它们发送消息,两台服务器都接收它并向客户端发送回复 - 我无法接收此回复。

服务器代码 -

 @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();
    }

服务器代码处的处理器 -

@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 " );
  }

客户端代码 -

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();
    }
  }

我确定在收听消息时我做错了什么。任何关于如何接收和处理来自多个服务器的消息的建议都会非常有帮助。

TIA

【问题讨论】:

  • “客户听”?
  • 描述运行它时会发生什么。错误信息?挂起?你试过调试器吗?
  • @slim 我不同意近距离投票和评论。 Maddie 描述了一个可以由该网络成员编译和调试的具体问题。请谨慎使用废话这个词,未使用的变量不是废话。
  • @PeterRader 除非您在定义当前未声明的变量时进行大量猜测,否则它不会编译。并且没有描述失败。
  • @slim 啊,我明白了:connections.out

标签: java sockets serversocket


【解决方案1】:

我面临两个问题:

1。你没有冲水。

out.write("收到你的消息" + message.toString());

2。在服务器中,您没有发送 \n

问题出在方法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();

来自Documentation

读取一行文本。一行被视为以换行符 ('\n')、回车符 ('\r') 或回车符后紧跟换行符中的任何一种来终止。

但是服务器既不发送\n也不发送\r。试试

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

【讨论】:

  • 谢谢@Peter Rader 我会尝试你的建议。
  • 添加新行并刷新有帮助。我正在为来自服务器的每条新消息创建一个新线程 - 有没有办法减少这些线程数?另外,我应该在什么时候销毁这些线程?
  • @maddie 线程可能是除了实例化之外具有特殊状态的最特殊类型的对象。一个线程可以运行,你是什么意思。一个线程的实例数还是正在运行的线程数?
  • 我想我不清楚。在 send(msg,i) 方法中,我正在创建一个新线程 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(); 这是我从服务器收到的每条消息创建一个线程。有没有更好的方法来处理这个?如何改为每台服务器只创建一个线程?
  • @maddie 这是一个很好的问题,但我没有足够的经验来回答这个问题。在 codereview 上发布您的问题可能会有所帮助。
猜你喜欢
  • 2018-04-04
  • 1970-01-01
  • 2016-08-31
  • 1970-01-01
  • 1970-01-01
  • 2016-02-06
  • 1970-01-01
  • 1970-01-01
  • 2018-08-23
相关资源
最近更新 更多