• Post Reply Bookmark Topic Watch Topic
  • New Topic

Socket.close(): Where to put it  RSS feed

 
Karen Baog
Ranch Hand
Posts: 120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,


Where should the socket.close() instruction be placed?
Here's a pseudo code:





And what about if the above is changed to socket.send()?


I have a test Server/client and I noticed that, as the Server prints out the Client port number, it (the Client port number) changes all the time.

 
Jeff Bosch
Ranch Hand
Posts: 805
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would put it in a finally() block, and close it if it's open. That way, whether or not an exception gets thrown, you still clean up by closing any open sockets...
 
Karen Baog
Ranch Hand
Posts: 120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Jeff,

This is what's on my test program:
Server.java



ServerThread.java


Where should the finally block be? The DatagramSocket is initialized inside the run() method in the ServerThread class.

Any chance you can provide the pseudo code?
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think the important question for me here is, why is socket an instance variable? That is, when you assign socket = new DatagramSocket(), will that DatagramSocket be used by any other code outside this thread (and this particular iteration of the while loop)? If so, you would need to tell us about what other code needs to use the socket. If not, then it's simple to make socket a local variable, and close it in the same block of code that created it:

This may look a little strange to you, having two try blocks in the method (one nested withing the other). However each one serves a different purpose, and needs to have a slightly different scope. Note that if the DatagramSocket constructor call fails, then no DatagramSocket has been created, and you couldn't possibly close it since no reference to the instance exists. That's why the second try block only begins after the constructor has completed.
[ July 14, 2005: Message edited by: Jim Yingst ]
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!