What is Sockets?


Sockets are used to provide the capability of making connections from one application running on one machine to another running on a different machine. A socket abstraction consists of the data structure that holds the information needed for communication, and the system calls that manipulate the socket structure. Once a socket is created, it can be used to wait for an incoming connection (passive socket) or can be used to initiate a connection (active socket).

A client can establish an active connection to a remote server by creating an instance of a socket. To establish a server connection and bind it to a particular port number, we should create an instance of a server socket. A server socket listens on a TCP port for a connection from a client (passive socket). When a client connects to that port, the server accepts the connection.

Once the connection is established, the client and server can read from and write to the socket using input and output streams. Streams are ordered sequences of data that have a source (input stream), or destination (output stream). Once the client or server finishes using the socket, the socket structure is de-allocated.

Client/Server Java Statement

The Socket class provides a client-side socket interface. A client can establish an active connection to a remote server by creating an instance of Socket as follows: Socket <connection>= new Socket (<host name>, <port number>);

The variable gives the name of the server to connect to; and <port number> should match the port number at the server end.

The ServerSocket class provides a server-side socket interface. To establish a server connection and bind it to a particular port number, we should create an instance of ServerSocket as follows −

ServerSocket <connection> = new ServerSocket(<port number>);

Once the connection is established, the client and server can read from and write to the socket using input and output streams. Streams in Java are used for Input/ Output. They are ordered sequences of data that have a source (input stream), or destination (output stream).

Updated on: 30-Jul-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements