【问题标题】:Having trouble receiving input from server for simple client/server无法从服务器接收简单客户端/服务器的输入
【发布时间】:2016-01-19 04:07:14
【问题描述】:

我正在处理一个简单的客户端/服务器。我必须将 cookie 从服务器发送到客户端(它只是一个字符串),但我的客户端不会读取 inputStream。

服务器:

 out = new PrintStream(sock.getOutputStream()); 

 out.println(text);
 out.println(temp2State);
 out.println(temp2State);

客户:

 in = new BufferedReader(new InputStreamReader(sock.getInputStream())); 

 String textClient = in.readLine();
 String temp1= in.readLine();
 String temp2= in.readLine();

这只是似乎给我带来麻烦的代码。在客户端我收到 textClient 但接下来的 2 是空白的。如果我在发送之前在服务器上打印出 temp2state,我会得到一个字符串,但是如果我在客户端上打印出 temp1,它是空的。所以它似乎在翻译中丢失了。话虽如此,如果使用 for 循环接收数据(在类中显示),它将返回 temp1 但 textClient 为空。这是在套接字上完成的,所以我确实有 try/catch,但它似乎并不相关。

备用输入读取:

for (int i = 1; i <= 5; i++) {
            fromServer = in.readLine();
            if (fromServer != null) {
                 String textClient = in.readLine();
                 String temp1= in.readLine();
                 String temp2= in.readLine();

             }}

找到问题:

原来我有一个字符串试图与附加的 System.lineSeperator() 一起发送,它正在发送一个空行。

【问题讨论】:

  • 您是否记得在完成打印语句后使用out.flush()out.close()
  • 是的,我在两者上都有 .close(),我尝试在它们上刷新,但似乎没有用。
  • 你在close()之前flush()了吗?

标签: java sockets


【解决方案1】:

根据 Java API, public PrintStream(OutputStream out)构造函数创建一个新的打印流,它不会自动刷新。

请尝试使用 with 构造函数,该构造函数接受 true 来自动刷新,只要数据写入其中。

请修改您的代码,如

out = new PrintStream(sock.getOutputStream(), true); 

【讨论】:

  • 感谢您的意见。几个小时前,我发现我返回的字符串 + System.lineSeperator() 实际上是一个问题,它返回的是空的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-03
  • 1970-01-01
  • 1970-01-01
  • 2012-04-28
  • 1970-01-01
  • 2017-12-29
相关资源
最近更新 更多