Introduction to Socket Programming

Introduction to Socket Programming

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.

  1. The value of any segment (byte) is between 0 and 255 (both included).
  2. There are no zeroes preceding the value in any segment (054 is wrong, 54 is correct).

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:

  • Network ID - To identify the ISP(internet service provider). The network part of the IPv4 address is on the left-hand side of the IP address. It specifies the particular network to where the IPv4 address belongs. IPs with same network bits value are said to be on the same network for example 10.1.8.62 and 10.3.5.34 are on the same network if these are class A addresses.
  • Host ID - To identify the hosts connected to a single provider. For example (1.8.62) is used to identify a single host if IP address(class A) is 10.1.8.62 .

No alt text provided for this image

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

  1. Server creates a new server socket, binds it to an available port (greater than 1024), the new ServerSocket(port) is used for this purpose.
  2. Server starts to listen on the port for incoming client connections using accept() function of ServerSocket class and accepts it
  3. The Client initiates the connection by binding a new Socket to the server port and IP, to initiate communication with the server.

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"));

    }
}        
No alt text provided for this image

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"));

    }
}        
No alt text provided for this image

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

  • https://www.cloudflare.com/en-gb/learning/network-layer/what-is-a-computer-port/
  • https://www.geeksforgeeks.org/introduction-of-classful-ip-addressing/
  • https://www.baeldung.com/a-guide-to-java-sockets

要查看或添加评论,请登录

Aneshka Goyal的更多文章

  • Introduction to Distributed Tracing

    Introduction to Distributed Tracing

    What is Distributed Tracing? The word tracing is to trace the request as it flows through the system. Since modern…

    2 条评论
  • Introduction to Service Discovery

    Introduction to Service Discovery

    What is Service Discovery? Service Discovery as the name suggests allows us to know or discover where each instance of…

  • Introduction to Micro frontend

    Introduction to Micro frontend

    What is Micro frontend? The term “micro frontends” debuted in the 2016 ThoughtWorks Technology Radar guide. At its…

  • Introduction to Pub-Sub and Streams with Redis&SpringBoot

    Introduction to Pub-Sub and Streams with Redis&SpringBoot

    Publish/Subscribe Problem: Let's say we have synchronous messaging between two components of our system called as…

    2 条评论
  • Introduction to Time Series Database - InfuxDB

    Introduction to Time Series Database - InfuxDB

    What is Time Series Data? As the title of the blog depicts we would be discussing about time series databases and in…

    1 条评论
  • Introduction to Ontology

    Introduction to Ontology

    What is Ontology? An ontology is a formal and structural description of knowledge about a specific domain. Knowledge is…

  • From Java 17 to Java 21 - Features and Benefits

    From Java 17 to Java 21 - Features and Benefits

    Java has been constantly evolving with new features and enhancements. With the recent LTS (Long term support) version…

    2 条评论
  • Vault Authentication and Springboot integration

    Vault Authentication and Springboot integration

    What is Vault? Vault is an identity-based secrets and encryption management system. A secret is anything that we want…

  • Introduction to gRPC with Spring boot

    Introduction to gRPC with Spring boot

    Overview RPC stands for remote procedure calls. In this the client is able to directly invoke a method on server…

    6 条评论
  • Introduction to Triple Crown

    Introduction to Triple Crown

    Organizations are always trying to improve how they work, in order to increase efficiency and reduce errors. This…

    4 条评论

社区洞察

其他会员也浏览了