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

查看:32
本文介绍了从 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.

但是除非服务器上的套接字关闭,否则我无法从服务器读取任何内容.服务器代码不受我的控制,无法对其进行编辑.

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天全站免登陆