gracefully ending socket communication

Hi. I have a client program and server program that communicate with a socket.

Here is the important code from the server:

ServerSocket server_socket =new ServerSocket(port);

while (true)

{

Socket socket = server_socket.accept();

InputStream is = socket.getInputStream();

BufferedReader br =new BufferedReader(new InputStreamReader(is));

PrintWriter out =new PrintWriter(socket.getOutputStream(),true);

String line;

while ( (line = br.readLine()) !=null)

{

out.println("server response");

}

br.close();

out.close();

}

Here is the important code from the client:

Socket client_sock =null;

BufferedReader in;

PrintWriter out;

try

{

client_sock =new Socket(ip_address, port);

out =new PrintWriter(client_sock.getOutputStream(),true);

in =new BufferedReader(new InputStreamReader(client_sock.getInputStream()));

String response ="";

out.println("client message");

String line;

while ( (line=in.readLine()) !=null)

{

response += line;

System.err.println(response);

}

}

catch (Exception e)

{

e.printStackTrace();

}

Here is my question: How do I actually send a "null" so that the loop

while ( (line=in.readLine()) !=null)

actually exits? I have tried sending a 0 (ascii null) and I have tried sending 23 (ascii end-of-transaction) and those don't work.

The only way I know how to stop the communication is to close the socket on one end, which results in an exception being thrown on the other end. I don't want to have a "Connection reset" exception. I just want the two parties to know that there are no more lines coming by reading the "null" and then gracefully move on.

Am I missing something about how socket communication is supposed to work? The way my code works now is that the server gets caught up in the readLine() loop waiting forever until I close the socket, which causes the server to barf.

[3129 byte] By [superiorlobea] at [2007-11-27 5:13:13]
# 1

You don't 'send a null', you close the socket at the sending end. This will cause the reading end executing the readLine() to receive a null.

You should always close the output sttream of a socket first, and once you've done that, closing the input stream and the socket itself are both redundant.

ejpa at 2007-7-12 10:34:41 > top of Java-index,Core,Core APIs...