Sockets, BufferedReader.readline() - why the stream is not ready?

后端 未结 2 823
-上瘾入骨i
-上瘾入骨i 2021-01-21 15:11

i\'m learning java and i faced some problems with sockets. I developed a simple client-server app - kind of knock-knock, it performs 4 steps:

  1. client sends some mes
相关标签:
2条回答
  • 2021-01-21 15:43

    You are using public PrintWriter(OutputStream out, boolean autoFlush) which will flush automatically on new line or println. It does not autoflush after every write. You have to flush after every write.

    Here is javadoc for the autoFlush param of the constructor: A boolean; if true, the println, printf, or format methods will flush the output buffer

    0 讨论(0)
  • 2021-01-21 15:53

    This might/might not solve your problem. But try keeping everything within Try Catch block. For eg: your ServerSocket initialization, writer blocks etc. If some error occurs, you might not be able to use writer anyhow, so there is no point in initializing it.
     You might try writing to standard output stream for debugging instead of a file. Below code for Server/ Client is a minor variant of yours and its working.

    Server:

        Socket socket;
        ServerSocket srvSocket;
        BufferedReader in;
        PrintWriter out;
        try {
            srvSocket=new ServerSocket(4444);
            socket = srvSocket.accept();
            out = new PrintWriter(socket.getOutputStream(), true);          
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out.println("test from server #1");
            out.println("test from server #2");
        } catch (IOException e) {
            e.printStackTrace();
        }
    

    Client

        Socket socket;
        BufferedReader in;
        PrintWriter out;
        String inStr;
        try {
            socket = new Socket("127.0.0.1", 4444);
            out = new PrintWriter(socket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            while ((inStr = in.readLine()) != null) {
                System.out.println(inStr);
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    
    0 讨论(0)
提交回复
热议问题