1

Hi i have a server socket that listens for requests from a client socket and my code doesnt seem to retrieve the data from its inputstream on data sent from the client socket.

below is the server socket code that listens for connections and handles the requests

  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();

        }

Here is my testcase

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());
        }


}
4

1 回答 1

2

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

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

于 2013-07-01T10:34:15.780 回答