【问题标题】:Java Socket server not recieving data from client socketJava Socket服务器未从客户端套接字接收数据
【发布时间】:2013-07-01 18:34:15
【问题描述】:

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

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

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


}

【问题讨论】:

    标签: java sockets serversocket


    【解决方案1】:

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

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

    【讨论】:

    • 好的,只要我在客户端调用 socket.write() 。我应该在适当的时候或之后关闭套接字吗?
    • 只要您希望接收循环停止。或者,更改接收循环。如果您想知道如何在保持套接字打开的同时发送数据,请查看 DataOutputStream 和 DataInputStream 的方法。或者,使用对象序列化、XML 等。
    猜你喜欢
    • 2013-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-19
    • 1970-01-01
    • 2012-03-05
    • 2017-04-30
    相关资源
    最近更新 更多