7

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

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

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

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

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

我怎样才能从客户端代码中克服这个问题。

谢谢

4

4 回答 4

14

看起来服务器可能没有发送换行符(这是 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();
于 2013-05-17T12:29:57.690 回答
8

为了在客户端和服务器之间进行通信,需要明确定义协议。

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

于 2013-05-17T12:30:16.813 回答
2

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

bis.readLine()

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

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

int bytesExpected = clientSocket.available(); //it is waiting here

int[] buffer = new int[bytesExpected];

int readCount = clientSocket.read(buffer);

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

于 2013-05-17T12:28:07.983 回答
0

这是我的实现

 clientSocket = new Socket(config.serverAddress, config.portNumber);
 BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

  while (clientSocket.isConnected()) {
    data = in.readLine();

    if (data != null) {
        logger.debug("data: {}", data);
    } 
}
于 2019-08-07T21:10:49.993 回答