我有一个Socket在某个x端口上侦听.
我可以从我的客户端应用程序将数据发送到套接字但无法从服务器套接字获得任何响应.
BufferedReader bis = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
String inputLine;
while ((inputLine = bis.readLine()) != null)
{
instr.append(inputLine);
}
Run Code Online (Sandbox Code Playgroud)
..此代码部分从服务器读取数据.
但除非服务器上的Socket关闭,否则我无法从服务器读取任何内容.服务器代码不受我的控制,无法对其进行编辑.
如何从客户端代码中克服此问题.
谢谢
小智 11
看起来服务器可能没有发送换行符(这是readLine()正在寻找的).尝试一些不依赖于此的东西.这是一个使用缓冲区方法的示例:
Socket clientSocket = new Socket("www.google.com", 80);
InputStream is = clientSocket.getInputStream();
PrintWriter pw = new PrintWriter(clientSocket.getOutputStream());
pw.println("GET / HTTP/1.0");
pw.println();
pw.flush();
byte[] buffer = new byte[1024];
int read;
while((read = is.read(buffer)) != -1) {
String output = new String(buffer, 0, read);
System.out.print(output);
System.out.flush();
};
clientSocket.close();
Run Code Online (Sandbox Code Playgroud)
要在客户端和服务器之间进行通信,需要很好地定义协议.
客户端代码阻塞,直到从服务器接收到一行,或者套接字关闭.你说只有在套接字关闭后你才收到东西.所以它可能意味着服务器不发送由EOL字符结束的文本行.readLine()
因此该方法阻塞直到在流中找到这样的字符,或者套接字被关闭.如果服务器不发送行,请不要使用readLine().使用适用于已定义协议的方法(我们不知道).
归档时间: |
|
查看次数: |
43686 次 |
最近记录: |