使用3个不同线程中的套接字侦听3个不同的端口

时间:2015-11-04 17:16:30

标签: java multithreading socketserver

我的主类使用3个线程的newFixedThreadPool定义ExecutorService对象。

public static void main(String[] args) {
    queue = new ArrayBlockingQueue<HashMap<String, String>>(MAX_QUEUE_LENGTH);
    socketThreads = Executors.newFixedThreadPool(3);

    socketThreads.submit(new MyListener(PORT1, queue));
    socketThreads.submit(new MyListener(PORT2, queue));
    socketThreads.submit(new MyListener(PORT3, queue));
}

提交了Runnables。 Runnables如下:

public class MyListener implements Runnable {

  private static ServerSocket listener = null;
  //	private Socket socket = null;
  private InputStream inStream = null;
  private OutputStream outStream = null;
  private static ArrayBlockingQueue < HashMap < String, String >> queue = null;

  private static Logger LOGGER = LogManager.getLogger(MyListener.class);
  int port;

  public MyListener(int port, ArrayBlockingQueue < HashMap < String, String >> queue) {
    try {
      listener = new ServerSocket(port);
      this.queue = queue;
      this.port = port;
    } catch (IOException e) {
      LOGGER.fatal("Could not connect to the socket, port number: " + port, e);
    }
  }

  @
  Override
  public void run() {

    do {
      try {
        LOGGER.debug("*** 1 ***");
        Socket socket = listener.accept();
        LOGGER.debug("*** 2 ***");

        ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
        HashMap < String, String > map = (HashMap < String, String > ) ois.readObject();

        LOGGER.debug("*** 3 ***");
        queue.add(map);

      } catch (IOException e) {
        LOGGER.fatal("Error in socket connection ", e);

      } catch (ClassNotFoundException e) {
        LOGGER.fatal("Error - Class not found ", e);

      } catch (ClassCastException e) {
        LOGGER.fatal("Error - Class Cast Exception ", e);
      }
    } while (true);
  }
}

因此,套接字基本上会读取传入的数据并将其添加到队列中。这个想法是,一旦请求进入并获得,套接字应该再次开始等待连接。当我运行单个线程池时,我的代码可以正常运行,但如果我启动了&gt;则无效池中有1个线程。正如您在代码中看到的那样,执行到达日志语句* * * 1 * * *并且接受永远不会发生。

我试图从中分离出ObjectnputStream并将其运行一个单独的runnable,但在阅读Creating a socket server which allows multiple connections via threads and Java之后这也无济于事。出现这种情况的原因是什么

1 个答案:

答案 0 :(得分:1)

  1. ServerSocket不应该是静态的。每次创建新的侦听器对象时都会覆盖它。

  2. 与接受的客户端有关的一切都在错误的地方:它的套接字及其两个流。这些应该是另一个Runnable类的非静态成员,该类被实例化以处理每个接受的套接字。