Reputation: 477
Hello i am studying an example of a server-client application and I do not understand how the client receives the string from the server.
The server runs a thread that does this:
String seq = generateSequence(l); //random stuff
outSocket.println(seq);
in the client class there is this code:
String serverSeq = inSocket.readLine();
System.out.println(serverSeq);
and inSocket
and outSocket
are implemented in the same way both in the thread and in the client classes, with:
inSocket = new BufferedReader(new InputStreamReader(socket.getInputStream()));
outSocket = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())), true);
where socket
is the same object too, it's the client's socket
My question is why serverSeq
string is exactly theseq
string? The server writes in the output stream, and the client picks up from the input stream, aren't those two different memory areas?
Upvotes: 0
Views: 934
Reputation: 477
Well the problem actually was that I thought server's accept()
function returned THE client's socket, but it doesn't, it returns a new socket that dialogues with the client's socket but they are two different objects, so inSocket
and outSocket
both in the client and in the server refer to two different sockets not the same one.
The server writes the string on its output stream and then it goes into the client's input stream which is quite logic, I was understanding that server was writing the string in the client's output stream and that didn't make sense.
Upvotes: 1
Reputation: 174
There's a lot of underlying software, and potentially hardware at play here if you are using sockets over network.
The implementation may be dependent on OS/platform, but in general a port will be open on both ends of the pc. Data will flow between the ports in some manner, likely through some sort of memory mapped I/O and then out to network or in local case perhaps just routed by cpu or memory commands. For local case, it's likely the data gets copied into the server socket's buffer/memory space, and the readline simply reads it and repositions the address pointer to indicate that data was read.
It's all hidden to you, so unless you work on the low level code for it, you don't need to care too much about how data is sent and received, but at minimum you should understand the different protocols commonly used(TCP, UDP, RAW).
EDIT: even if you use localhost, it's likely to go out to network controller of your system and then just loopback. It's unlikely system optimizes it to bypass network controller and just copies direct to the receiving socket.
Upvotes: 0