Can I Have Two-Way Communication with Sockets with just one Port?
Joined: Oct 22, 2011
I've had some success working with sockets. I can start a Java program on one machine that I'll call the server, and can then start another Java program on another machine that I'll call the client, and I can have the first program on the server use a socket to send information to second program on the client.
In this situation the communication is in one direction only; the server sends the client information; the client doesn't appear to be able to send the server any information. What I'd like to do is make my communication two-way; I'd like to be able to send information from the server to the client, but also be able to send information from the client to the server.
My guess was that I would have to open another socket to get this done. Is that true? Is there another way to establish the two-way communication that I'd like to have?
And my real question is, if I do have one socket for the server to send data to the client, and another socket for the client to send data to the server, does that mean I need to open one socket on one port and the other socket on another port? That is to say, is it possible to use the same port for both sockets, and if it is, is there any way that might mess up my two-way communication?
My question is, how do I use my <stSocket> in program <Multiply> on 10.72.77.49 to send the product back to the <stSocket> in program <SendTwo> so it can print it out?
Obviously this is an extremely simple process, just multiplying two numbers, but I kept it simple to make the problem simple, so I could understand how I can establish two-way communication with one socket.
Is it simply a matter of replacing the comment in <Multiply> with a declaration of an <OutputStream> object and setting it equal to <stSocket.getOutputStream()> like I did in <SendTwo>, and then doing a <write( product)> on that object? And then replacing the comment in <SendTwo> with a declaration of an <InputStream> object and setting it equal to <stSocket.getInputStream()> like I did in <Multiply> and then doing a <read()> on that object? If so, do I have to close the previously declared <iStream> and <oStream> objects before I create the new <OutputStream> and <InputStream> objects?
If it isn't this simple, how can I get two-way communication with this simple example?
I don't see what your problem is. Clearly you know how to write to a socket. And clearly you know how to read from a socket. So what's stopping you from doing what you're already doing, but in the other direction?