简体   繁体   中英

Multithreaded connections handling

I want to write a server which listens on the given port for connections and puts sockets into BlockingLinkedQueue from which the consumer thread will read messages. I accept incoming connections in this way:

   ServerSocket serverSocket = new ServerSocket(port);
   while (true)
   {
        Socket socket = null;
        socket = serverSocket.accept();
        queue.put(socket);
   }

When I try to connect in parallel from two separate hosts it occurs that responses to the first one are sent to the second one after establishing the second connection. When I change my code to this listed below the second connection is merely refused:

   while (true)
   {
        ServerSocket serverSocket = new ServerSocket(port);
        Socket socket = serverSocket.accept();
        queue.put(socket);
   }

My questions are:

  1. What's the difference between this two situations? Why in the first situation messages are sent to the second host?
  2. How should I refactor my code in order to create separate connections between my server and both hosts and handle them in parallel?

What's the difference between this two situations?

In the first case, you are using the same port for multiple connections. In the second case, you are discarding the server port so any waiting connections for be refused.

Why in the first situation messages are sent to the second host?

Due to a bug in code, not shown here.

How should I refactor my code in order to create separate connections between my server and both hosts and handle them in parallel?

Create a thread for each connection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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