Socket problem - readline won't work properly
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).
Here is some of the code.
Server:
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 InputStr开发者_运维百科eamReader(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();
Replace write() with println() here.
OK, I made several editing in the code and now it run nicely :
The server :
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());
}
}
I change the readline with read and it work, so the assumption that "\n" is the problem is correct.
The thread : a minor change in the thread (remove the reading request part since I already done that in the server)
The Client: change the readline into read just like the server one.
Thank you all for the help
out.write("My message");
That doesn't send a line terminator so it can never be read. Use println().
out.println(clientResponse+"\n");
That will send the clientResponse plus a newline plus a \n. The last part will probably be interpreted as a blank line. Not much point in that. Remove the \n.
do{
response = in.readLine(); //This is where the code hang
}while (response.length()<= 0);
That's not the correct way to read lines. It will get an NPE at EOS; the response length can never be negative; and why would you send yourself blank lines? The correct way is this:
while ((response = in.readLine()) != null) {
// if (response.length() == 0) continue; // if you must
// process the line
}
// when you get here EOS has occurred.
Could it be because clientResponse
(sent by server thread) is null
and the client is waiting for response size > 0?
According to the javaDoc, the server response actually is
"My Message:\n"+System.getProperty("line.separator")
I bet, in.readLine()
works fine at least once - but you just ignore the response, because the print command is outside the loop. Move that one up, and you should see the responses on the console.
There is a (very small) chance, that the servers println()
doesn't really send a \n
char. So you could try this at the thread code:
out.print(clientResponse+"\n\n"); // exchanged println with an extra \n char
精彩评论