IntelliJ Java IDE
The moose likes Sockets and Internet Protocols and the fly likes Calling an open socket server Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Sockets and Internet Protocols
Reply Bookmark "Calling an open socket server" Watch "Calling an open socket server" New topic
Author

Calling an open socket server

Mike Cunningham
Ranch Hand

Joined: Nov 14, 2000
Posts: 128
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

Joined: Jan 12, 2005
Posts: 37
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

Joined: Nov 14, 2000
Posts: 128
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

Joined: Aug 07, 2003
Posts: 1646
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.
 
 
subject: Calling an open socket server
 
Threads others viewed
Can I Have Two-Way Communication with Sockets with just one Port?
Calling an open socket server
Connect to a socket server using applet
Java Socket Programming
Socket programming
WebSphere development made easy
without the weight of IBM tools
http://www.myeclipseide.com

cast iron skillet 49er

more from paul wheaton's glorious empire of web junk: cast iron skillet diatomaceous earth rocket mass heater sepp holzer raised garden beds raising chickens lawn care CFL flea control missoula heat permaculture