Reputation: 167
I m started networking in java and hava some questions.Can anyone clear these to me? What is the difference between sockets and server sockets? Is ServerSocket means something related to server?
Upvotes: 1
Views: 68
Reputation: 581
Yes, I can explain it to you: A ServerSocket
is the server-side socket. It needs an open port in your firewall and LISTEN for OTHER clients to connect to your computer. A 'normal' Socket
just ASK a server for a connection. This does not need an open port in your firewall. Everything, that you do in the internet, requires, that your computer ASK a server in the internet, for a connection. But the server have to LISTEN for a connection. So with the ServerSocket
, you can accept those requests and create a connection:
ServerSocket server = new ServerSocket(<port>);
Socket client = server.accept();
This is the serverside code and it creates a ServerSocket to listen for connection requests and create a normal Socket to use this connection. A Client application will connect like this:
Socket skt = new Socket(<ip>, <port>);
This will also create a socket
, that can use the connection. But it requires a serverSocket
, that accepts the connection request.
Hope, that helped you
Cydhra
P.S English is not my mother language, so I am sorry for mistakes.
EDIT:
Can u please explain me what does server.accept() do
This method waits until a client requests a connection. So if your application shall do something while waiting for connections, you should use a thread, because your programm will stop until server.accept() get a request.
server.accept() waits for a client requesting a connection with this server on the specified port. When a client requests such a connection, the accept()-Method will return a instance of Socket, that represent the Client. It contains the Input- and Output-Streams, that can be used to send and recieve data from the client.
Socket skt = new Socket(<port>, <ip>);
This is the code of the client, as I posted above. It also contains the input- and outputstreams. Everything, that you write in the OutputStream of one Socket, will be recieved by the InputStream, of the other Socket. The Sockets are like Files, with two ends: On one end, you write in, on the other side, you can read the written.
Upvotes: 2