套接字问题 - readline无法正常工作 [英] Socket problem - readline won't work properly
本文介绍了套接字问题 - readline无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试使用套接字编写客户端和服务器连接。问题是我的客户端无法从服务器读取响应(它挂在readline上)。
I try to code a client and server connection using socket. The problem is my client can't read the response from the server (it hangs on the 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());
}
}
线程:
The Thread:
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();
}
}
客户:
The client:
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();
}
}
你能告诉我这是什么问题吗?非常感谢你的帮助
Could you guys tell me what's the problem? Thank you very much for any help
推荐答案
好的,我已经把这个问题搞定了。它不是挂起的客户端,而是服务器。它尝试从客户端读取一行文本,但客户端不发送行分隔符:
Okay, I've figured this one out. It's not the client that hangs, it's the server. It tries to read a line of text from the client, but the client doesn't send the line separator:
out.write("My message");
out.flush();
在这里用println()替换write()。
Replace write() with println() here.
这篇关于套接字问题 - readline无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文