套接字,BufferedReader.readline()-为什么流未准备好? [英] Sockets, BufferedReader.readline() - why the stream is not ready?

查看:55
本文介绍了套接字,BufferedReader.readline()-为什么流未准备好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Java,但我遇到了一些套接字问题。我开发了一个简单的客户端-服务器应用程序-一种敲门程序,它执行4个步骤:

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. 客户端向服务器发送一些消息

  2. 服务器将它们接收并保存到文件中

  3. 服务器将一些其他消息发送回客户端

  4. 客户端将它们接收并还保存到文件中

  1. client sends some message to server
  2. server recieves them and saves to file
  3. server sends back to client some other messages
  4. client recieves them and also saves to file

问题出现在第4步:客户端不接收消息,也永远不会循环:

Problem appears on step #4: client doesn't recieve messages and never gets out the loop:

while ((inStr = in.readLine()) != null) {
    writer.println(inStr);
}

其中in是 BufferedReader

    try {
        socket = new Socket(ipAddress, 4444);
        out = new PrintWriter(socket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

在服务器端发送消息:

    try {
        socket = srvSocket.accept();
        out = new PrintWriter(socket.getOutputStream(), true);          
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));                
    } catch (IOException e) {
        e.printStackTrace();
    }

...

    out.println("test from server #1");
    out.println("test from server #2");

在客户端,我在in.ready() c>-返回false。在服务器端,我看着 out.checkError()-它返回true;

on client side i watched in.ready() - it returns false. On server side i watch out.checkError() - it returns true;

我在做什么错-为什么流是空的吗?

What am i doing wrong - why is the stream empty ?

任何帮助我感激不尽! :)

Any help ia appreciated! :)

推荐答案

您正在使用 public PrintWriter(OutputStream out,boolean autoFlush)会自动刷新到新行或 println 它不会在每次写入后自动刷新。您必须在每次写入后刷新。

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.

以下是构造函数的autoFlush参数的javadoc:
一个布尔值;如果 true println printf format 方法将刷新输出缓冲区

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

这篇关于套接字,BufferedReader.readline()-为什么流未准备好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆