Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Socket programming: checking if server is alive

132 views
Skip to first unread message

Timo

unread,
Oct 25, 2001, 7:35:05 AM10/25/01
to
I have a simple Java client, which feeds data to a
server, but doesn't require any responses, i.e the data stream
is from client to server only. However, how can my client detect
whether server has closed the socket or not? If the server
closes the socket, my client should try to re-establish the
connection once in a while, so much data wouldn't be lost.

I create a write to socket this way:

socket = new Socket(server, port);
output = new PrintWriter(socket.getOutputStream(),true);

output.println(msg);

I checked the Java documentation about Socket and PrintWriter
classes, but couldn't find any solutions. PrintWriter.println
doesn't seem to return an error or throw and exception when server
closes the socket.

The only way I have managed to check whether the server is alive
is the create a backround thread for reading data in a loop
from server, although server doesn't send anything:

String resp = input.readLine();
if (resp==null) {
System.out.println("null received, break...");
break;
}

This seems to work, although I don't know if there are more
elegant methods available. Any comments?

BR,
Timo

Gordon Beaton

unread,
Oct 25, 2001, 7:42:27 AM10/25/01
to
On 25 Oct 2001 04:35:05 -0700, Timo wrote:
> I have a simple Java client, which feeds data to a server, but
> doesn't require any responses, i.e the data stream is from client to
> server only. However, how can my client detect whether server has
> closed the socket or not? If the server closes the socket, my client
> should try to re-establish the connection once in a while, so much
> data wouldn't be lost.
>
> I create a write to socket this way:
>
> socket = new Socket(server, port);
> output = new PrintWriter(socket.getOutputStream(),true);
>
> output.println(msg);
>
> I checked the Java documentation about Socket and PrintWriter
> classes, but couldn't find any solutions. PrintWriter.println
> doesn't seem to return an error or throw and exception when server
> closes the socket.

Exactly.

Use a BufferedWriter instead, which will throw an exception if you
attempt to write after the server has closed the connection.

/gordon

--
[ do not send me private copies of your followups ]
g o r d o n . b e a t o n @ e r i c s s o n . c o m

0 new messages