简体   繁体   中英

Server accept socket but after that the socket cannot receive anything

I've encountered a very strange problem (since this always worked before) when building a client-server chat program.

The serversocket accepts without any problem the incoming connection of the client, but when I try to read from the socket's inputstream the whole method blocks and only releases when I close the client's socket.

I've even tried it with the sample code on docs.oracle.com, but the problem remains.

Can anybody point me out the error I'm obviously not seeing?

Server code:

public class Server {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws IOException {
    System.out.println("Creating server socket");

    ServerSocket internetSocket = new ServerSocket(60000);
    if(!internetSocket.isClosed()) {

        while(true) {
            Socket s = internetSocket.accept();
            System.out.println("accepted socket!");

            BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream()));

            String line = null;
            while((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        }
    }
}
}

Client code:

public class Client {

public static void main(String[] args) throws IOException {
    Socket s = null;
    try {
        s = new Socket("localhost", 60000);
    } catch (UnknownHostException ex) {
        Logger.getLogger(Start2.class.getName()).log(Level.SEVERE, null, ex);
    }

    PrintWriter outStream = new PrintWriter(s.getOutputStream());
    for(int i=0; i<10; i++) {
        outStream.println("test");
        System.out.println("Sending the message \"test\"");

        try {
            Thread.sleep(5000);
        } catch (InterruptedException ex) {
            Logger.getLogger(Start2.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    s.close();
}
}

You forgot to add a true as the 2nd parameter when creating the printwriter printwriter

new PrintWriter(s.getOutputStream(), true);

It will make it flush automatically.

the method readLine() is waiting for \\n character to appear in the stream (the method blocks until it sees end line delimeter).

Try sending "test\\\\n" from the client and see what happens.

And remember to flush() the output stream on the client side

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