dcsimg
Socket close detection
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Mark_Minasazi
Posted On:   Monday, July 14, 2003 10:56 AM

I use the following code in my application on both client and the server.

			
output = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"UTF8"));

input = new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF8"));


It works fine but there is one problem. The problem is that the server side doesn't promptly catch that the client is disconnected and therefore the socket is closed. I think the problem is in BufferedReader. Is there any fix to this? Or is there another Reader or Writer that recognizes socket disconnection promptly and supports UTF8?


Thanks

Re: Socket close detection

Posted By:   Chun_Tse  
Posted On:   Tuesday, July 29, 2003 05:51 AM

How do you check to see if the client has disconnected?



I can't remember where I got this example from. I've slightly modified it to send a response back. The program accepts connections on port 1500. Prints any messages received to stdio and sends a "Got it" message back. If the message is NULL then it knows that the client has disconnected.



You can compile and run it as is. Then use telnet 1500 to test. To disconnect in telnet use ']'.



package tcpServer;



import java.net.*;

import java.io.*;



public class tcpServer {



/** Creates a new instance of tcpServer */

public tcpServer() {

}



/**

* @param args the command line arguments

*/

public static void main(String[] args) {

int port;

ServerSocket server_socket;

BufferedReader input;

BufferedWriter output;



try {

port = Integer.parseInt(args[0]);

}

catch (Exception e) {

System.out.println("port = 1500 (default)");

port = 1500;

}

try {

server_socket = new ServerSocket(port);

System.out.println("Server waiting for client on port" +

server_socket.getLocalPort());

// server infinite loop

while (true) {

Socket socket = server_socket.accept();

System.out.println("New connection
accepted " +

socket.getInetAddress() +

":" + socket.getPort());

input = new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF8"));

output = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"UTF8"));



// print received data

try {

while(true) {

String message = input.readLine();

if (message==null) {

System.out.println("Message is null");

break;

}

System.out.println(message);

try {

output.write("Got It");

output.flush();

}

}

catch (IOException e) {

System.out.println(e);

}

}

}

catch (IOException e) {

System.out.println(e);

}


// connection closed by client

try {

socket.close();

System.out.println("Connection closed by client");

}

catch (IOException e) {

System.out.println(e);

}

}

}

catch (IOException e) {

System.out.println(e);

}

}



}


About | Sitemap | Contact