• Post Reply Bookmark Topic Watch Topic
  • New Topic

Calling an open socket server  RSS feed

 
Mike Cunningham
Ranch Hand
Posts: 130
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a program that calls another java program whose basic purpose is to open a server socket, listen for a response, and then close the server socket.

I would prefer to open the socket for responses once and be able to get a handle on it when needed.

If anyone can inform me of the process for this or throw in a snippit of code to get me started I would really appreciate it.

Thanks,

Mike
 
Elihu Smails
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am not sure what you mean by "I have a program that calls another java program" Are you talking about one Java class that calls another java class?

You should just open a ServerSocket, and have the ServerSocket.accept pass the returning Socket off to logic that will handle the connection.
 
Mike Cunningham
Ranch Hand
Posts: 130
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, it's a java program calling another java program. I use the ServerSocket.accept() method to get a handle on the server socket. The part that I'm unclear about is how to
pass the returning Socket off to logic that will handle the connection
for the multiple sessions that take place in this application.
 
David Harkness
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ServerSocket.accept() returns a new Socket with I/O streams for the connected client. Since you want to handle multiple simultaneous clients (do you?), you can't handle I/O with the client right there in that thread.

Instead, you create a new Thread (or grab one from a ThreadPool) and give it the Socket to handle client I/O.

Then you continue in your accept loop, calling ServerSocket.accept() for the next client connection.

The easiest way is to have one Thread for the accept loop and one Thread per client connection. The class that will handle client I/O could look something like this:Your server's accept loop would be like this:Obviously, you'll need to fill those out a bit.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!