TCP is a Network Protocol which stands for Transfer Control Protocol, that allows well founded communication between applications. TCP is consistently used over the Internet Protocol, and that is why referred as TCP/IP. The communication mechanism between two systems, using TCP, can be established using Sockets and is known as Socket Programming. Hence, socket programming is a concept of Network Programming, that suggests to write programs that are executed across multiple systems, which are connected to each other using a network.

Mechanism for Socket Programming

A client creates a socket at it’s end of transmission, and strive to connect the socket to server. When a connection is established, server creates a socket at it’s end and, client and server can now ready communicate through writing and reading methods. Following is the elaborated procedure of what happens when a TCP connection is established:

  1. An object of ServerSocket is instantiated, and desired port number is specified, on which connection is going to take place.
  2. The accept method of ServerSocket is invoked, in order to hold the server in listening mode. This method won’t resume until a client is connected to the server through the given port number.
  3. Now, on client side, an object of Socket is instantiated, and desired port number and IP address is specified for the connection.
  4. An attempt is made, for connecting the client to the server using the specified IP address and port number. If attempt is successful, client is provided with a Socket that is capable of communicating to the respective server, with write and read methods. If unsuccessful, desired exception is raised.
  5. Since a client is connected to the server, accept method on the server side resumes, providing a Socket that is capable of communicating to the connected client.
  6. Once the communication is completed, terminate the sockets on both, the server and the client side.

Now, communication is held using input/output streams of Sockets. The InputStream of client is coupled with the OutputStream of server and OutputStream of client is coupled with the InputStream of server. Since, TCP is a two-way network protocol, hence information can flow through both the streams at the time.

#tcp-ip #java #socket-programming #client-server #sockets

TCP/IP Socket Programming in Java
2.30 GEEK