Introduction to Socket Programming
Aneshka Goyal
AWS Certified Solutions Architect | Software Development Engineer III at Egencia, An American Express Global Business Travel Company
What is a socket?
Socket is one endpoint of a two-way communication link between two programs running on the network. Each socket is a combination of IP(Internet Protocol) address and port number.Sockets are a concept on transport layer of the TCP/IP model.
Ports
In order to understand sockets we need to have understanding of what is a port. Port is a number used to identify an application running on a machine. Ports are virtual points where the network connections start and end. Ports are managed by the operating systems. Port numbers are represented by 16bits and hence value range is 0-65535. Not all ports out of these can be used by our applications that we develop.
Port numbers are divided into ranges as follows:
Port numbers 0-1023 – Well known ports.?These are allocated to?server services?by the?Internet Assigned Numbers Authority?(IANA). e.g Web servers normally use?port 80(HTTP)and SMTP servers use?port 25 for mail servers. These are assigned and controlled port numbers.
Ports 1024-49151- Registered Ports?-These can be registered for services with the?IANA?and should be treated as?semi-reserved.?User written programs should not use these ports. Registered ports are used by vendors for their server applications. These are not assigned or controlled, but can be registered to prevent duplication e.g., the value 1,512 was registered by Microsoft for use by its NetBIOS Name Services implementation, commonly known as Windows Internet Name Services [WINS]
Ports 49152-65535 - Dynamic Ports– These are used by?client programs?and we are free to use these in client programs. When a Web browser connects to a web server the browser will allocate itself a port in this range. Also known as?ephemeral ports. These can be used by clients for making connections that are not supposed to last long and hence are dynamic. These are free to use and are not assigned, controlled, or registered.
Ports are ports. Irrespective of whether we are talking about TCP or UDP a port number is a 16-bit binary integer that identifies a program currently executing on a given host. The range of possible values is 0 to 65,535; however, the value 0 is reserved and implies an unspecified source or destination.
Another important part of a socket is IP address.
IP stands for internet protocol address. It is a logical address of a machine in a network. An IP address (IPV4) is a 32 bit unique address having an address space of 2^32. IP address can be represented in dot notation or in using hex representation. IP address is divided into 4 segments each of 8bits.
The 32 bit IP address is divided into five sub-classes by InterNic. These are:
Class A,Class B,Class C,Class D and Class E
The order of bits in the first octet determine the classes of IP address. The first three classes are for host addressing while the class D is for multicast and E for research purposes by Internet Engineering Task Force.
IPv4 address is divided into two parts:
IP addresses can be allocated statically or dynamically. It is preferred to allocate IPs statically to network devices like routers or servers while the end user devices can have dynamically allocated IPs via the Dynamic Host Configuration Protocol (DHCP).
Subnetting is another interesting topic under IP addresses, subnets are basically dividing one network into two or more smaller networks.It increases routing efficiency, enhances the security of the network and reduces the size of the broadcast domain.
Subnet masks are used to separate the network and host bits of an address. The default subnet masks for class A, B, C of IP addresses are 255.0.0.0, 255.255.0.0 and 255.255.255.0 respectively. Subnet masks are created setting all the network bits to 1 and all host bits to 0.Thus it helps to identify and separate the network and host bits in an address making it easy for a router to route package to same subnet(local) or remote network or subnetwork.
Note1: the all 0s and all 1s in host address(binary) are never used because all 0s in host is nothing but the network address and all 1s are used to broadcast the packet to all hosts within the subnet/network
领英推荐
Note2: The Internet Protocol (IP) specifies a loopback network with the (IPv4) address?127.0.0.0/8. Most IP implementations support a loopback interface (lo0) to represent the loopback facility. Any traffic that a computer program sends on the loopback network is addressed to the same computer. In simple words this can be treated as IP address for localhost
Client - Server socket sequence of events
In the code below we have a server application running on localhost(loopback IP) and port 2306. The server creates multiple threads to accept concurrent client requests(by different clients). It is able to receive and send messages to the client applications.
Server Application Code
Main method to start the server - on port 2306
public class MainServer {
public static void main(String[] args) throws IOException {
new Server().start(2306);
}
}
Once the server is started, it starts listening for incoming client connections on the port 2306 and for each client connection accepted, it starts a new thread to handle the client-server communication
public class Server {
private ServerSocket serverSocket;
public void start(int port) throws IOException {
serverSocket = new ServerSocket(port);
while(true) {
new ClientHandler(serverSocket.accept()).start();
}
}
}
ClientHandler implements the Thread class and has a run method, this is called whenever a new thread is started and holds all the logic to read and write to the socket
public class ClientHandler extends Thread{
private Socket clientSocket;
private BufferedReader in;
private PrintWriter out;
public ClientHandler(Socket clientSocket) {
this.clientSocket = clientSocket;
}
public void run() {
try {
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
if ("end" .equals(inputLine)) {
out.println("good bye");
break;
}
out.println(inputLine);
}
in.close();
out.close();
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Following code snippet is to depict 2 client applications that connect to the server and read and write some messages
Client 1
public class Client {
private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;
public void startConnection(String ip, int port) throws IOException {
clientSocket = new Socket(ip, port);
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
}
public String sendMessage(String msg) throws IOException {
out.println(msg);
String resp = in.readLine();
return resp;
}
public static void main(String[] args) throws IOException, InterruptedException {
Client client = new Client();
client.startConnection("127.0.0.1",2306);
System.out.println(client.sendMessage("hello its me client"));
System.out.println(client.sendMessage("end"));
}
}
Client 2
public class ClientTwo {
private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;
public void startConnection(String ip, int port) throws IOException {
clientSocket = new Socket(ip, port);
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
}
public String sendMessage(String msg) throws IOException {
out.println(msg);
String resp = in.readLine();
return resp;
}
public static void main(String[] args) throws IOException, InterruptedException {
ClientTwo client = new ClientTwo();
client.startConnection("127.0.0.1",2306);
System.out.println(client.sendMessage("hello its me client 2"));
System.out.println(client.sendMessage("end"));
}
}
Both clients connect to the server on loopback address 127.0.0.1 as the server is on localhost(local machine) and on port 2306. As can be seen a server socket, listening for connections can connect to multiple clients simultaneously. The theoretical limit is 2^16-1 and each connection is represented by a quadruple(client port, client ip, server port and server ip) and needs to be unique. But practically its limited my the hardware and OS resources.Client Port, it can send one connection request per port that is this particular client port will be used exclusively to connect to the server that we created above.
Sources of knowledge