When I started to work here I was creating a web server for learning, but I did't have a chance to complete it.
So recently, I started to work on it again to have a better understanding about the web.
In this article, I'm going to right about how networking between a client and a server works.
To start off, let's make a simple client and a server.
Client.java
package client; import java.net.Socket; public class Client { public static void main(String[] args) throws Exception { try(Socket socket = new Socket("localhost", 8001)) { } catch (Exception e) { e.printStackTrace(); } } }
Server.java
package server; import java.net.ServerSocket; import java.net.Socket; public class Server { public static void main(String[] args) throws Exception { try(ServerSocket serverSocket = new ServerSocket(8001)) { System.out.println("Waiting for a client"); Socket socket = serverSocket.accept(); System.out.println("Client connected!"); socket.close(); } catch (Exception e) { e.printStackTrace(); } } }
When you run the client after running the server, the client tries to connect to the server.
But how exactly does that happen? I summarized this process down below.
1. Creating a socket
At first, the server creates a socket. Sockets are like an entrance and an exit on each side of a pipe. When a socket is made in Server.java above, it will wait for a connection from another socket at port 8001 (Outputs "Waiting for a client"). There also will be a descriptor (a number assigned to a socket) returned. The application will keep a record of that number on its memory, and it will distinguish sockets according to this number.
2. Connecting a pipe to the server's socket
"new Socket("localhost", 8001) creates a stream socket, and connects to the specified port number (Outputs "Client connected!").
In order to connect to the desired socket accurately, an IP address and a port number is necessary. (It's basically the same as sending a letter. The IP address is like an address of a building, and the port number is like the name of the person you are sending the letter to.)
3. Transmitting and receiving data
The data will be transmitted via a network. Then, the server returns a response. The memory space for storing the received message is called a receive buffer.
4. Disconnecting the pipe and erasing the socket
Disconnects the pipe. It doesn't matter whether you disconnect it from the server or the client. Erase the socket afterwards.
I hope this clears up questions regarding sockets!
Original article written by: Ryosuke Uchitate
Translated by: Yu Koga