套接字问题 - readline无法正常工作

时间:2010-12-16 06:13:20

标签: java sockets

我尝试使用socket编写客户端和服务器连接。问题是我的客户端无法从服务器读取响应(它挂在readline上)。

以下是一些代码。

服务器:

    try {
        // Create the server socket.
        portNumber = Integer.parseInt(myParam.get("socket.portNumber"));
        System.out.println(portNumber);
        mainSocket = new ServerSocket(portNumber);

    } catch (IOException ioe) {
        System.out.println("Error Message : "+ioe.getMessage());
    }

    while(true)
    {     
        try
        {
            // Accept connections
            Socket clientSocket = mainSocket.accept();
            SocketServerThread st = new SocketServerThread (clientSocket);
            st.start();
        }
        catch(IOException ioe)
        {
            System.out.println("Error message :"+ioe.getMessage());
        }
    }

主题:

public void run() {

    BufferedReader in = null;
    PrintWriter out = null;
    String clientResponse = null;

    try {
        in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        out = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()));

        //Read The Message
        String clientRequest = in.readLine();
        System.out.println("Message recieved : " + clientRequest);

        //Process the message

        // Send response
        out.println(clientResponse+"\n");
        out.flush();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        // Clean up
        try {
            in.close();
            out.close();
            clientSocket.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }

客户:

    try {
        // Create the server socket.
        simSocket = new Socket("192.168.52.27", portNumber);
    } catch (IOException ioe) {
        System.out.println("Error Message : " + ioe.getMessage());
    }
    BufferedReader in = null;
    PrintWriter out = null;
    try {
        in = new BufferedReader(new InputStreamReader(simSocket.getInputStream()));
        out = new PrintWriter(new OutputStreamWriter(simSocket.getOutputStream()));

            out.write("My message");
            out.flush();

            do{
            response = in.readLine(); //This is where the code hang
            }while (response.length()<= 0);

            System.out.print(response);

    } catch (IOException ioe) {
        System.out.println("Error message :" + ioe.getMessage());
    } finally {
        try {
            in.close();
            out.close();
            simSocket.close();
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }
你可以告诉我这是什么问题吗?非常感谢你的帮助

5 个答案:

答案 0 :(得分:8)

好的,我已经把这个想出来了。它不是挂起的客户端,而是服务器。它尝试从客户端读取一行文本,但客户端不发送行分隔符:

    out.write("My message");
    out.flush();

在这里用println()替换write()。

答案 1 :(得分:2)

好的,我在代码中做了几次编辑,现在运行得很好:

服务器:

    try {
        // Create the server socket.
        portNumber = Integer.parseInt(myParam.get("socket.portNumber"));
        mainSocket = new ServerSocket(portNumber);

    } catch (IOException ioe) {
        System.out.println("Error Message : " + ioe.getMessage());
    }

    // Accept connections    
    try {
        clientSocket = mainSocket.accept();
    } catch (IOException ioe) {
        System.out.println("Error Message : " + ioe.getMessage());
    }
    BufferedReader in = null;
    PrintWriter out = null;

    while (true) {
        try {
            in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            out = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
            //Read The Message
            **StringBuffer buffer = new StringBuffer();
            while (true) {
                int ch = in.read();
                if ((ch < 0) || (ch == '\n')) {
                    break;
                }
                buffer.append((char) ch);
            }
            String clientRequest = buffer.toString();**

            SocketServerThread st = new SocketServerThread(clientRequest, out);
            st.start();
        } catch (IOException ioe) {
            System.out.println("Can't accept connection. Error message :" + ioe.getMessage());
        }
    }

我用read读取readline并且它有效,所以假设“\ n”是问题是正确的。

线程: 线程中的微小更改(删除读取请求部分,因为我已经在服务器中完成了该操作)

客户: 将readline更改为read,就像服务器一样。

谢谢大家的帮助

答案 2 :(得分:0)

可能是因为clientResponse(由服务器线程发送)是null而客户端正在等待响应大小&gt; 0?

答案 3 :(得分:0)

根据javaDoc,服务器响应实际上是

"My Message:\n"+System.getProperty("line.separator")

我打赌,in.readLine()至少工作一次 - 但你只是忽略了响应,因为print命令在循环之外。移动那个,你应该在控制台上看到响应。

服务器println()实际上没有发送\n字符的可能性非常小。所以你可以在线程代码中尝试这个:

 out.print(clientResponse+"\n\n");  // exchanged println with an extra \n char

答案 4 :(得分:0)

out.write("My message");

这不会发送行终止符,因此永远无法读取。使用println()。

out.println(clientResponse+"\n");

这将发送clientResponse加上换行加上\ n。最后一部分可能会被解释为空行。没那么重要。删除\ n。

do{
    response = in.readLine(); //This is where the code hang
}while (response.length()<= 0);

这不是读取线条的正确方法。它将在EOS获得NPE;响应长度永远不会是负面的;你为什么要给自己留空线?正确的方法是:

while ((response = in.readLine()) != null) {
    // if (response.length() == 0) continue; // if you must
    // process the line
}
// when you get here EOS has occurred.
相关问题