繁体   English   中英

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

[英]Java Socket server not recieving data from client socket

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

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

  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为止,因为您的客户端没有关闭套接字,EOS永远不会到达。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM