Java socket server -> Only accepts one request then stops accepting?

核能气质少年 提交于 2019-12-12 04:44:44

问题


I'm trying to write a simple socket server for a project of mine, but it only accepts one request and then doesn't accept anything else from anywhere.

public void run() {
    println("Socket server running...");
    try {
        sock = new ServerSocket(20424);

        while(true) {

            clientSocket = sock.accept();

            PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
            BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

            String data;

            while((data = in.readLine()) != null) {
                println("[SocketServer] " + data);
                if(data.equalsIgnoreCase("COUNT(TRIGGERS)")) {
                    out.println(getTriggerCount());
                }               
            }
            out.println("endOfStream");

            out.close();
            in.close();
            clientSocket.close();
        }
    }  catch (IOException e) {
        e.printStackTrace();
    }
}

It will accept one request and respond with the correct amount of data, but after that nothing works. Here's the client I'm using to connect:

public static void main(String[] args) {
    try {
        socket = new Socket("localhost", 20424);
        out = new PrintWriter(socket.getOutputStream(), 
                true);
        in = new BufferedReader(new InputStreamReader(
                socket.getInputStream()));

        out.println("COUNT(TRIGGERS)");

        String data;

        while((data = in.readLine()) != null) {
            System.out.println(data);
        }

        socket.close();
    } catch (UnknownHostException e) {
        System.out.println("Unknown host");
        System.exit(1);
    } catch  (IOException e) {
        System.out.println("No I/O");
        System.exit(1);
    }
}

回答1:


It will accept the next connection as soon as the inner while ends...

Maybe you want to create socket handlers for the incoming connections with their own threads, so you can handle multiple connections simulatanously.



来源:https://stackoverflow.com/questions/12771360/java-socket-server-only-accepts-one-request-then-stops-accepting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!