The concept of Socket can be daunting at first. In this tutorial, we are going to talk about Socket in great detail. You may or may not have heard the term “Socket is an Application Programming Interface or API“. In this tutorial, you are going to know why Socket is regarded as an “API“. You are going to realize how Socket may make your life simple. We are talking about your programming life, of course! We can do nothing about your social life.
However, Socket helps you to write your Network Applications without having to worry about all the low-level networking details. When you use Socket, all the low-level networking details are taken care of by the built-in libraries provided by the language. In our case, Java provides us with all the necessary libraries to connect and communicate programs over the network. One of the main benefits of using Java as a Networking Programming Language is that sending and receiving data over a network can be regarded as just I/O with a slightly different connection at the end of the I/O chain. With Java, you can make a full-fledged network-aware application in a very short time. That means more free time on your hand. You can use this free time wisely to improve your social life. In this way, Socket can not only improve your programming life but also your social life too.
Consider the following analogy to better understand processes and sockets.
A Transport Analogy
Assume your friend Sam enjoys collecting old books. Her favorite book is Harper Lee’s To Kill a Mockingbird. You walk past this old bookstore one day and come across a first edition of To Kill a Mockingbird. You recall that her birthday is coming up next week. You buy the book in order to give it to her on her birthday. However, there is only one setback. Last month, she relocated to a different state. And you are unable to travel right now in order for her to receive the book before her birthday.
So you go to a courier service and package the book. Sam gets it on her birthday. Everyone is happy. So what is a courier company?
A courier company (also known as a delivery service company or express service company), is a company that specializes in the transportation of packages and documents. They provide a range of services like same-day, next-day, and scheduled delivery. They may also provide international shipping. Courier companies typically offer a variety of options for package pickup and delivery, including door-to-door service and pickup and delivery at designated locations. If you’ve ever purchased something online(like amazon, eBay, etc.), you know what we are talking about.
Courier companies use various means of transportation such as cars, motorcycles, vans, trucks, trains, and airplanes to deliver packages. Moreover, they have different levels of service depending on the urgency of the delivery and the distance to be covered.
In short, courier companies provide a fast, reliable and efficient way to send and receive packages and documents. They offer different levels of service to meet the needs of different customers.
You do not have to know every tiny bit of detail about the courier company. You only need to figure out that they are trustworthy and reliable. After all, your only concern is that the parcel arrives on time and in good condition. You do not have to know the mode of transportation used to deliver your package. Or the number of trucks they have. Or how many employees they have. Or the number of warehouses they have. You only care that your package arrives at Sam undamaged and on time. The courier service handles all of the heavy lifting. You simply go to the courier service office, register the parcel, pay, and sign some paperwork.
A courier service can be thought of as similar to a process in networking. Notice we are talking about the service the courier company provides, not the company itself. Just as a courier service picks up packages from various locations and delivers them to their destinations, a process in networking picks up data packets from various sources and delivers them to their intended recipients.
A Socket can be thought of as similar to a "pickup point" in this analogy. Just as a "pickup point" is a designated location where packages can be dropped off or picked up by the recipient or a designated agent, a Socket is a designated location in a computer's memory where data packets can be sent or received. A Socket is a "logical representation". You can not go and search for a "physical socket" in your machine. You will no find any.
The sender(You) and receiver(Sam) does not know or care how the parcel is transported. They just care that the packet is sent and received in time without any damage.
In short, the sending process sends the data packets to the Socket and the receiving process receives the data from the Socket. The processes do not “exchange” the messages(in networking we call them packets) directly with each other. They use a Socket as an intermediary(in our networking jargon “interface”).
Data is transmitted across the Internet in finite-size packets known as datagrams. Each datagram is made up of a header and a payload. The header contains the destination address and port, the source address and port, a checksum to detect data corruption, and various other housekeeping information used to ensure reliable transmission.
The actual data is encapsulated in the payload. However, due to the limited length of datagrams, it is frequently necessary to split the data across multiple packets and reassemble it at the destination. It’s also possible that one or more packets are lost or corrupted in transit and must be resent, or that packets arrive out of order and must be reordered. Keeping track of this—splitting the data into packets, generating headers, parsing the headers of incoming packets, keeping track of which packets have and haven’t been received, and so on—requires a lot of work and intricate code. If you’ve gone through our Networking Fundamentals tutorial series, you’ll understand how frames and packets are structured. We won’t get into it here.
Fortunately, you are not required to do the work yourself. Sockets enable programmers to treat a network connection as just another stream into which bytes can be written and read. Sockets protect the programmer from low-level network details like error detection, packet sizes, packet splitting, packet retransmission, network addresses, and so on.
The diagram above depicts socket communication between two processes communicating over the Internet. The diagram assumes that the processes’ underlying transport protocol is the Internet’s TCP protocol (we will talk about it in a minute or two). A socket, as depicted in this diagram, is the interface(we talked about “interface” in the previous tutorial) between the Application Layer and the Transport layer within a host.
Because the socket is the programming interface with which network applications are built, it is also referred to as the Application Programming Interface (API) between the Application and the Network. The application developer has complete control over the application-layer side of the socket but little control over the transport-layer side. The application developer’s only control over the transport layer is (1) the choice of transport protocol and (2) the ability to set a few transport-layer parameters such as maximum buffer and maximum segment sizes. When an application developer selects a transport protocol (if a choice is available), the application is built taking advantage of the transport-layer services provided by that protocol.
Socket Is An Application Programming Interface(API)
Let us remind you again that a Socket is a software interface. A Socket provides us with a standardized way for processes to communicate over a network. Think of the Socket as a bridge between the Application Layer and the Transport Layer. This bridge allows you to exchange data or packets or messages, whatever you call it, without having to deal with or worry about the details of the underlying network protocols. Both the Client-Server and Peer-to-Peer network architectures use Sockets.
Because the socket is the programming interface with which network applications are built, it is also referred to as the Application Programming Interface (API) between the Application and the Network. The application developer has complete control over the application-layer side of the socket but little control over the transport-layer side. The application developer’s only control over the transport layer is (1) the choice of transport protocol and (2) the ability to set a few transport-layer parameters such as maximum buffer and maximum segment sizes. When an application developer selects a transport protocol (if a choice is available), the application is built taking advantage of the transport-layer services provided by that protocol.
Think of Socket as a wormhole. A wormhole hypothetically provides a shortcut for travel or communication between two distant points. It is visualized as a tunnel-like structure that connects two separate regions of space-time. Through this tunnel objects or information can pass from one region to another.
A socket can be compared to a wormhole in the sense that both provide a path or a connection between two points. A socket provides a connection between two applications, allowing them to communicate with each other over a network.
Just as a socket defines a set of standardized protocols for communication between applications, a wormhole defines the rules and conditions for movement between the two points in space-time. Both provide a path for communication or movement, and both have a set of defined rules and conditions that govern that communication or movement.
You put an object in the wormhole and it appears in the other side of the destination point. You do not have to know what happens in the wormhole. All you care is that your object appears undamaged on the other side. Same goes for the Socket. You put some data into a Socket form your program and appears in the destination program. You do not care how that data has traversed the network. All you care about is that the data is not corrupted and damaged.
We will be demonstrating Network Programming with Socket later in this tutorial. Before we can show you how to do Socket Programming in Java you have to understand how to address a process.
How To Address A Process
Let us first explain why you need to address a process. Consider the example of the Courier Service. To send a parcel to a specific destination, the destination must have an address. If you want to send the book to Sam, you must give the courier company her address. Similarly, in order for a process running on one host to send packets to another, the receiving process must have an address. Two pieces of information must be specified to identify the receiving process:
(1) The address of the host and
(2) An identifier that specifies the receiving process in the destination host
The host on the Internet is identified by its IP address. In Connecting Networks Using Routers, we went over IP addresses in depth. For the time being, all we need to know is that an IP address is a 32-bit number that can be thought of as uniquely identifying the host.
In addition to knowing the address of the host to which a message is destined, the sending process must also identify the receiving process (more specifically, the receiving socket) running in the host.
This information is required because a host may be running multiple network applications. This is accomplished through the use of a destination port number. A network port is a communication endpoint on a computer or network device, such as a router or server, that allows it to connect to other devices on a network. The port number is a 16-bit unsigned integer, thus ranging from 0 to 65535. Commonly used port numbers are assigned by the Internet Assigned Numbers Authority (IANA) and are typically used for specific types of network services, such as HTTP (port 80) for web traffic and HTTPS (port 443) for secure web traffic. Network administrators can also configure devices to use non-standard port numbers for specific applications or services.
This concludes the port. We won’t go into specifics about the port. For networking programming, all you need to know about a port is that it is a number ranging from 0 to 65535. To identify a process in a Host, an IP address and port number are required.
Socket Programming In Java
We promised you in the previous section that we would show you how to use Socket in Java. In the following section, we will look at how to use Socket in Java. Socket programming in Java involves creating sockets to establish connections between machines to send and receive data. A socket is an endpoint for sending or receiving data across a computer network.
Here is an example of how to create a simple socket program in Java:
Server side
import java.net.*;
import java.io.*;
import java.util.*;
public class TimeServer {
public static void main(String args[]) throws Exception {
ServerSocket serverSocket = new ServerSocket(2500); //create server socket on port 2500
System.out.println("Server Started...");
while (true) {
System.out.println("Waiting For Connection ...");
Socket clientSocket = serverSocket.accept(); // wait for client to connect
System.out.println("Client connected: " + clientSocket.getInetAddress().getHostAddress());
DataOutputStream output = new DataOutputStream(clientSocket.getOutputStream());
output.writeBytes("Server Date: " + (new Date()).toString() + "\n");
output.close();
clientSocket.close();
}
}
}
Client Side
import java.io.*;
import java.net.*;
public class TimeClient {
public static void main(String args[]) throws Exception {
Socket connection = new Socket(InetAddress.getLocalHost(), 2500); // create socket and connect to server on port 1234
System.out.println("Connected to server: " + connection.getInetAddress().getHostAddress());
BufferedReader input = new BufferedReader(new InputStreamReader(connection.getInputStream()));
System.out.println(input.readLine());
}
}
This example shows a simple server-client program that uses a TCP socket to send and receive data. The server creates a ServerSocket object on a specified port and waits for a client to connect. When a client connects, it creates a new Socket object to communicate with the client. The client creates a Socket object and connects to the server on the specified port. Once connected, the server and client can send and receive data using the InputStream and OutputStream of the Socket object. In this Application the server program sends the current date when the client asks it from him.
If you want to learn more about how to use Socket in Java, we recommend that you click on this link. To learn how to run a client-server program in Java, click here.
In the next tutorial, we will be discussing the Transport Services available to network applications and how you may choose them.