从Java套接字读取数据 [英] Read Data from a Java Socket

查看:122
本文介绍了从Java套接字读取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Socket侦听某个x端口。

I have a Socket listening on some x port.

我可以从我的客户端应用程序将数据发送到套接字但无法从服务器套接字获得任何响应。

I can send the data to the socket from my client app but unable to get any response from the server socket.

  BufferedReader bis = new BufferedReader(new 
  InputStreamReader(clientSocket.getInputStream()));
  String inputLine;
  while ((inputLine = bis.readLine()) != null)
  {
      instr.append(inputLine);    
  }

..此代码部分从服务器读取数据。

.. This code part reads data from server.

但除非服务器上的Socket关闭,否则我无法从服务器读取任何内容。
我无法控制服务器代码来编辑其中的内容。

But I cant read anything from server until unless the Socket on the server is closed. Server code is not under my control to edit something on it.

如何从客户端代码中克服此问题。

How can I overcome this from client code.

谢谢

推荐答案

要在客户端和服务器之间进行通信,需要很好地定义协议。

To communicate between a client and a server, a protocol needs to be well defined.

客户端代码阻塞,直到从服务器收到一行,或者套接字关闭。你说只有在套接字关闭后你才收到东西。所以它可能意味着服务器不发送由EOL字符结束的文本行。因此, readLine()方法会阻塞,直到在流中找到这样的字符,或者套接字被关闭。如果服务器不发送行,请不要使用readLine()。使用适用于定义的协议的方法(我们不知道)。

The client code blocks until a line is received from the server, or the socket is closed. You said that you only receive something once the socket is closed. So it probably means that the server doesn't send lines of text ended by an EOL character. The readLine() method thus blocks until such a character is found in the stream, or the socket is closed. Don't use readLine() if the server doesn't send lines. Use the method appropriate for the defined protocol (which we don't know).

这篇关于从Java套接字读取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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