Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Networking (Socket) question.  RSS feed

 
Tommy Becker
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've been playing around with the basic chat client code from Head First Java. I extended the initial example to be able to talk to more than 1 client at a time using threads. For those that aren't familiar with the book, the client connects to the server and the server simply sends it a string containing "advice". Anyway, I set it up to loop so once you connect to the server, it sends you a continous stream of advice, about 1 every second. Multiple clients can connect and that works fine. My question is how do I determine when the client is no longer there? If I kill a client using ^C, the server thread sending the data to that client just keeps on trucking. I've tried using the isConnected() method of the socket class to see if the connection is still good but the behavior is the same. I realize that a proper client would call close() but that's not the point. Surely there has to be a way I can tell that the client bailed from the server side. . .
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moving to Sockets and Internet Protocols...
 
hatim osman
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there...
I am not sure if I clearly understood your question but here is a remark that may be useful:

when working with sockets, any attemp to read or write to a socket that is disconnected "became unreachable after initially was reachable" will throw SocketException. Therefore you can continue send data to a remote client, however, if the client disconnects then an Exception will be thrown. It's a good practice to handle any clean up code in a finally block :



Hope this is helpful.
Hatim
 
Tommy Becker
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the reply. I too thought that it would throw an exception, but it doesn't seem to. Here is the class that is sending the data:


I'm catching any and all exceptions there, no? Anyway, when a client connects, I start a thread that runs this code and it never exits, even after I ^C on the client.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!