简体   繁体   中英

Java TCP Socket

I'm having blocking issue when trying to read the InputStream from a socket.
Here is the code for the server side :

public static void main(String[] args) throws Exception {
    if (args.length != 1) {
        throw new IllegalArgumentException("Parameter : <Port>");
    }

    int port = Integer.parseInt(args[0]); // Receiving port

    ServerSocket servSock = new ServerSocket(port);
    String s;
    Socket clntSock = servSock.accept();
    System.out.println("Handling client at "
            + clntSock.getRemoteSocketAddress());
    in = new BufferedReader(
            new InputStreamReader(clntSock.getInputStream()));
    out = new PrintWriter(clntSock.getOutputStream(), true);

    while (true) {
        s = in.readLine();
        System.out.println("s : " + s);
        if (s != null && s.length() > 0) {
            out.print(s);
            out.flush();
        }
    }
}


Here is the client part where I'm sending and receiving the data (String) :

while (true) {
    try {
        // Send data
        if (chatText.getToSend().length() != 0) {
            System.out.println("to send :"
                    + chatText.getToSend().toString());
            out.print(chatText.getToSend());
            out.flush();
            chatText.getToSend().setLength(0);
        }

        // Receive data
        if (in.ready()) {
            System.out.println("ready");
            s = in.readLine();
            System.out.println("s : " + s);
            if ((s != null) && (s.length() != 0)) {
                chatText.appendToChatBox("INCOMIN: " + s + "\n");
            }
        }

    } catch (IOException e) {
        cleanUp();
    }
}


The readLine method is blocking the client thread running the above code. How can i avoid that problem ? Thanks for helping.

The readLine method is blocking the client thread running the above code. How can i avoid that problem ?

readLine is a blocking operation. If you use multiple threads this doesn't have to be a problem.

You are using readLine() on the client which expects lines ending with EOL tokens, but your server-side code is not writing EOL tokens. Use println() instead of print() .

To support concurrent clients, on the server you'll need to spin off threads to handle accepted connections:

while (true) {
    // Accept a connection
    Socket socket = servSock.accept();

    // Spin off a thread to deal with the client connection
    new SocketHandler(socket).start();
}

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