Win a copy of Head First Agile this week in the Agile forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Servlets and Sockets -- Concerns?  RSS feed

 
Adrian Marti
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey people,

Writing a small webapp which takes some user data and then connects to a legacy server app over UDP sockets over our intranet. It seems to be working fine but I was wondering what pitfalls i should be on the lookout for when doing socket programming from inside a j2ee app server. The server is weblogic btw. I only send 2 messages and open 1 port for each request. I make sure to close the socket on exit and exception catches. Is there anything else I should do? Or any advice on ways to make sure this works correctly?

Thanks,

Adrian
 
Anthony Watson
Ranch Hand
Posts: 327
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My advice is to use local variables because class level variables are not threadsafe.
 
Jeroen Wenting
Ranch Hand
Posts: 5093
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
correct. Use class level variables only for data you want available to all instances of the servlet (and even then keep in mind that this isn't guaranteed to work, for example on clustered systems it won't work that way) running inside the JVM.

This more or less limits it to constants (port number might be a good one for this, and servername to connect to, things like that).

Apart from that, make sure you do all communication with the backend in a single HTTP request. Do not think to open a socket during one request and close it again during another, this is asking for trouble.
Some things can be done with storing the open socket in the HTTP session and closing it when the session terminates (you'll need a session listener for that to ensure it also happens when a session times out rather than being closed normally) but it's still a bit dodgy.
 
Adrian Marti
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
great thanks! I'm only doing the socket stuff in one http request as u advised. I'll also be careful with my variables. It seems to be working fine.

Thanks again.

Adrian
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!