A socket is a mechanism by which two systems can communicate over the network. In Unix-based operating systems, socket is an extension of the concept of pipe. Hence, sockets can be used in a similar way of pipe. But there is a clear difference that a socket can be used to establish communication between two computers, which are connected over the network. Using socket, a process running in one system can communicate to a process that is running in a different system.
Sockets are used in designing client/server communication. For example, remote login (rlogin), File Transfer Protocol, etc uses a socket to establish a connection between server and client.
How Socket Works?
Before designing and developing simple applications, first, we will discuss how Sockets work? Thus to understand it, first, we will discuss how sockets are used on the server-side and how it is used on the client-side?
Server Side
First of all, a socket is created in the server application. It's a resource like a file descriptor that is assigned to the server process alone. It can't be shared with other processes.
After creating a socket server process assigns a name to the socket. For local sockets a filename from the filesystem is assigned, generally from /tmp or /usr/tmp directory. Whereas, for network sockets, the filename will be a service identifier, by which clients can communicate. This name assignment is performed by the bind system call. This identifier allows Linux to route incoming connections specifying a particular port number to the correct server process.
Then, the server process waits for a client to connect and a queue is created for incoming connections using listen system call.
A client request is accepted by the server using accept system call. When the system call accept is called, a distinct new socket is created which is used only for the communication with the particular client.
To design a multi-client application, the same-named socket (prepared earlier using bind system call) can be used.
If multiple client requests are received on the server-side, client requests are kept in listen queue until the server is ready to accept.
Client Side
In the client-side application, an unnamed socket is created by calling socket. Then, it calls connect to establish a connection with the server by using the server's named socket as an address. After establishing the connection, sockets can be used like low-level file descriptors for communicating with the server.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.