从Java套接字读取数据

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

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

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

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

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

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

谢谢

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

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

看起来服务器可能没有发送换行符(这是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(); 

对我来说,这段代码很奇怪:

 bis.readLine() 

我记得,这会尝试读入缓冲区,直到找到'\n' 。 但是,如果从未发送过怎么办?

我丑陋的版本打破了任何设计模式和其他建议,但始终有效:

 int bytesExpected = clientSocket.available(); //it is waiting here int[] buffer = new int[bytesExpected]; int readCount = clientSocket.read(buffer); 

您还应该添加错误和中断处理的validation。 有了webservices结果,这对我有用(2-10MB是最大的结果,我发送的)