gpt4 book ai didi

Java Socket 服务器未从客户端套接字接收数据

转载 作者:行者123 更新时间:2023-11-30 04:19:39 25 4
gpt4 key购买 nike

嗨,我有一个服务器套接字,它监听来自客户端套接字的请求,而我的代码似乎没有从客户端套接字发送的数据的输入流中检索数据。

下面是监听连接并处理请求的服务器套接字代码

  public void startlistener() {
serverSocket = new ServerSocket(PORT);
listening = true;
thread.start();
Log.print(TAG, "startlistener");

}

public void stopListener() {
thread.stop();
listening = false;
Log.print(TAG, "stopListener");
}

public void run() {
while (listening) {
try {

Log.d(TAG, "inside server listener loop");
Socket accept = serverSocket.accept();

String data = getData(accept);

httpHandler.handleRequest(data, accept);

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

private String getData(Socket socket) throws IOException {
InputStream in = socket.getInputStream();
Log.print(TAG, "getData");
int c = 0;

StringBuffer buffer = new StringBuffer();
//goes as far as here and then freezes/doesnt retrieve anything from the input stream
while ((c = in.read()) != -1) {
buffer.append((char) c);
}
return buffer.toString();

}

这是我的测试用例

private static final String HTTP_REQUEST = "HTTP/1.0 408 Request Time-out"
+ newLine + "Cache-Control: no-cache" + newLine
+ "Connection: close" + newLine + "Content-Type: text/html";

public void testSocketConnection() {

try {
httpProxy = new HttpProxy(testHttpHandler);
httpProxy.startlistener();
testSocket = new Socket("localhost", HttpProxy.PORT);
OutputStream outputStream = testSocket.getOutputStream();
InputStream inputStream = testSocket.getInputStream();

outputStream.write(HTTP_REQUEST.getBytes());
} catch (UnknownHostException e) {
httpProxy.stopListener();
e.printStackTrace();
fail(e.toString());
} catch (IOException e) {
httpProxy.stopListener();
e.printStackTrace();
fail(e.toString());
}


}

最佳答案

您的客户端没有关闭套接字。您的服务器读取套接字直到 EOS,由于您的客户端没有关闭套接字,因此它永远不会到达。

NB 不在接受线程中处理客户端 I/O。启动一个单独的线程。

关于Java Socket 服务器未从客户端套接字接收数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17402183/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com