43

If Socket represents client side and ServerSocket represents server side, why Socket.read reads the data from server side? I'm really confused, Can you please clarify it to me?

Alex Weitz
  • 2,451
  • 2
  • 24
  • 41
sevugarajan
  • 8,831
  • 12
  • 32
  • 30

9 Answers9

46

(I post this answer because I always feel it's important to make the logic right.)

I suggest you take a look at the following sample.

http://docs.oracle.com/javase/tutorial/networking/sockets/clientServer.html

Admittedly, when carrying out TCP/IP communication, all the necessary information can be provided by the Socket class alone for the sole purpose of communication. No matter it is on server side or client side.

As you can see from the above link, server side use the following code to acquire its own Socket instance. That is, another socket is created on the same server local port and the client port pair.

enter image description here

Then, server use this Socket instance to talk to the client.

And to make the picture complete, below code snippet shows client's Socket instance.

enter image description here

So if Socket can do it all already, why do we still need the ServerSocket?

This is because of the working paradigm of communication over TCP/IP protocol.

When 2 programs talk over TCP/IP, usually one will passively listen/wait on a <IP:port> and the other one will actively connect to it.

So you can see, at this very starting phase of the communication, the 2 sides have very different behaviors. So 2 different classes are used to reflect this difference.

  • Socket class encapsulates the behavior of the active side. (a.k.a. the client)
  • ServerSocket class encapsulates the behavior of the passive side (a.k.a. the server)

Once the ServerSocket accomplished its listening task and detected an incoming connection, it will accept() it and create a new Socket instance to facilitate the communication.

Similarily, in java.nio package, you will find ServerSocketChannel and SocketChannel classes. And still, they behave like this:

ServerSocketChannel -------------> SocketChannel
                      accept()

So, to some extent, I agree with @JohnK as he pointed out in the comment, it's more or less just a 6-letter difference.

smwikipedia
  • 52,824
  • 76
  • 267
  • 432
  • 3
    Don't provide information as image which can be text. – Karl Richter Aug 01 '17 at 18:56
  • 2
    @KarlRichter It's for better high-lighting. – smwikipedia Aug 01 '17 at 22:35
  • "That is, another socket is created on another port." This might be misleading since the new socket uses the same port as the one the server is listening on. If your `ServerSocket` listens on port 443, the new `Socket` will also use port 443 and the client's ephemeral port. – Matthias Braun Sep 09 '19 at 08:20
  • 1
    Yes, I'm positive. You can convince yourself by cloning and starting [this simple server](https://gitlab.com/bullbytes/simple_socket_based_server) which uses `ServerSocket`. Doing `curl -k "https://localhost:8443/"` will show that the `socket` (created from `accept()`) for sending TCP packets to the client and the `serverSocket` used for accepting new client connections both use 8443 as the local port. The code in question is [here](https://gitlab.com/bullbytes/simple_socket_based_server/blob/master/src/main/java/com/bullbytes/simpleserver/Start.java#L68). – Matthias Braun Sep 09 '19 at 09:17
  • @MatthiasBraun Thanks. You are correct. I refined the answer. It is the pair of ports defines the socket. The link in my answer also details that. – smwikipedia Sep 09 '19 at 09:33
  • Would it be better if the `Socket` class were named as `Connection`? It seems `ServerSocket` is really one socket (one IP + one port), whereas upon successfully creation, `Socket` is actually a TCP connection containing two sockets, i.e. both the client and the server endpoints. – wlnirvana Nov 24 '19 at 12:03
12

why socket.read reads the data from serverside

Because it is reading the data sent by the server through the network, it is not reading directly the server filesystem or resouces ( db , ram or anything like that ) it is reading the data that was already processed by the ServerSocket.

Think about the Socket as your web browser and the ServerSocket as the remote webserver.

When you request an image, page, etc, the webserver ( The ServerSocket ) writes the bytes to the client, in turn the client has to read them ( to know what the webserver sent right? ) and process them by displaying them to the final user.

The same happend with ServerSocket/Socket but at a lower level. The socket reads information from the ServerSocket.

Does it make sense?

OscarRyz
  • 184,433
  • 106
  • 369
  • 548
9

First of all, let's clarify what IS Socket look like: in a common case, Socket is a concatenation of IP and port via :, for example: 127.0.0.1:8080.

So, you decided to make client-server application using Socket. There's nothing too much complicated. Here's short explanation about making connection between client and server:

  1. First of all, let's clarify that fact, that our client have his own Socket and knows server IP address and port. For server there are provided only ServerSocket and port. In both cases port are the same number between 0 and 65535.
  2. So, we decided to connect our client to our server:

    • client creates his Socket clientSocket object with known IP and port of our server.

    • server got incoming connection request with his ServerSocket.accept() method, which generates new Socket newClientSocket object (still on a server side (!) ).

    • Further data exchanging goes via clientSocket and newClientSocket objects (not between clientSocket and ServerSocket).

Here is almost perfect picture to understand the basic connection process (keep in mind, that Socket object on Client at this picture - same objects).

After you've made this simple structure, you need to open two streams on both Client.clientSocket and Server.newClientSocket sides for reading and writing information.

SuppieRK
  • 197
  • 2
  • 11
  • Your *Here* link led me to the original post. https://codethat.wordpress.com/2010/01/14/coffee-time-with-java-part-1-sockets It is a wonderful socket/serversocket crash tutorial .... Thanks! – Sym-Sym Jun 16 '18 at 23:19
  • that image you attached cleared almost all my doubts. thank you so much. – Aniket Jadhav Jul 30 '19 at 13:02
  • @SuppieRK Assuming I have 100 Server.newClientSocket objects, all of themwill use the same server port for sending and receiving data to their corresponding client-sockets ? – OAH May 19 '20 at 20:26
8

java.net.ServerSocket

This class implements server sockets. A server socket waits for requests to come in over the network. It performs some operation based on that request, and then possibly returns a result to the requester.

java.net.Socket

This class implements client sockets (also called just "sockets"). A socket is an endpoint for communication between two machines.

Marc Juchli
  • 2,090
  • 21
  • 18
1

ServerSocket is again a Socket with additional features of server endpoint. The server features includes listening to the port and accepting an incoming connection etc...

ArunDhaJ
  • 581
  • 5
  • 17
1

Take a look at http://java.sun.com/docs/books/tutorial/networking/sockets/

Carnell
  • 739
  • 6
  • 10
  • Whilst this may theoretically answer the question, [it would be preferable](//meta.stackoverflow.com/q/8259) to include the essential parts of the answer here, and provide the link for reference. – Karl Richter Aug 01 '17 at 18:57
1

ServerSocket is created to bind to a port and listen for a connect from a client. So, a server just waits for a conversation and doesn't start one.

ClientSocket is created to connect to a listening server. The client initiates the connection.

Example: Think of an inbound call center as an example. These services are servers. They don't initiate a call but wait for a call to come in from clients. Once the calls are in, they can engage in a two way conversation.

Karl Richter
  • 6,271
  • 17
  • 57
  • 120
0

Because it's reading what has been sent to you by the server.

Noon Silk
  • 51,625
  • 6
  • 84
  • 103
0

Socket is for the client side and ServerSocket is for the server side.

Karl Richter
  • 6,271
  • 17
  • 57
  • 120
Sunil Kumar Sahoo
  • 49,865
  • 50
  • 172
  • 240