开发者

Java ServerSocket won't accept new connections until close() is called on the accepted socket

In my code (below) the the serverSocket won't accept a new connection until a thread deals with the existing connection and calls close() on the socket that serverSocket.accept() created. If i start this server and open two tabs in the browser then only one of the tabs connects and the other is left waiting until the other tab finishes (which it doesn't) before serverSocket.accept() will accept a new connection. How can i accept a new connection without closing the previous one?

public class ReboundServer {

    static Se开发者_如何学编程rverSocket serverSocket;
    public static boolean listening = true;

    /**
     * @param args
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException {     
        try {
            serverSocket = new ServerSocket(4444);

            System.out.println("Starting Server");
        } catch (IOException e) {
            System.out.println("Could not listen on port: 4444");
            System.exit(-1);
        }       

        while(listening)
        {
            (new Thread(new ClientThread(serverSocket.accept()))).start();
        }

        serverSocket.close();
    }
}  

public class ClientThread implements Runnable {
    private Socket clientSocket = null;

    public ClientThread(Socket socket)
    {
        this.clientSocket = socket;
    }

    public void run()
    {
        System.out.println("ClientConnected");
        MatchThread.QueueLock.lock();
        MatchThread.connectionQueue.add(clientSocket);
        MatchThread.QueueLock.unlock(); 

    }
}


Obviously the problem is not here but in the MatchThread class whose code you haven't posted. It appears you have a single thread dealing with that queue. Why?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜