Codecademy Logo

Sockets

What is TCP?

Transmission Control Protocol (TCP) is a communication protocol that enables applications to exchange messages over a network and ensure the successful delivery of exchanged data packets. Due to its reliability, TCP is the favored protocol for many types of common applications.

Diagram comparing data flow in TCP.

Sockets

A socket is an endpoint that essentially allows us to connect the client and server using transmission control protocol.

Client-Server Architecture

Client-server architecture is made up of the following:

  • Client - A tool (computer or software) used to request data from a server.
  • Server - A tool (computer or software) used to respond to client requests.
  • Request/Response - Communication model used by computer to communicate over a network.

Creating a ServerSocket

To create a ServerSocket in java, use the following code:

ServerSocket firstServerSocket = new ServerSocket(6868);

DataInputStream

A DataInputStream allows a program to read primitive data from an underlying input stream, while a DataOutputStream is used to write the primitive data.

Port Numbers

A socket is tied to a specific port number so that data can be sent between the client and server.

Learn More on Codecademy