Socket programming using TCP and UDP

By | January 27, 2016 | 171 Views


This note is to learn how to build client/server application that communication using TCP and UDP sockets focusing on application layer. Socket is “door” between application process and end-transport protocol.

Socket Programming

Figure 1: Socket “door” in the internet protocol stack.

Two sockets types of two transport services: UDP (unreliable datagram), and TCP (reliable, in-order byte stream-oriented). A table below shows differences between the TCP (Transmission Control Protocol) and UDP (User Datagram Protocol).

TCP service UDP service
Connection-oriented Provide connection setup between client and server processes Connectionless
Reliable transport Reliable data transfer between sending and receiving processes by using flow control, sequence numbers, acknowledgements, and timer Unreliable
Flow control Sender will not overwhelm receiver No
Congestion control Throttle sender when network overloaded No
Does not provide Timing, minimum throughput guarantees, security (no encryption, and cleartext passwords sent into socket traverse Internet) The same with TCP

In this note, we will use a simple client-server application to demo how the socket programming works for both TCP and UDP.

  1. Client reads a line of data (characters) from its keyboard and sends the data to the server.
  2. The server receives the data and count how many characters.
  3. The server sends the counted characters to the client.
  4. The client receives the counted characters and show it in console line of the client.

TCP Implementation

TCP Socket Diagram

Figure 2: The client-server application using TCP.

Now let’s take a look at the server and client program implemented by Java.

public class TCPClient {
	public static void main(String[] args) throws Exception {
		String sentence = "";
		String modifySentence = "";
		// Reads text from a character-input stream - its keyboard by creating a
		// stream object inFormUser type of BufferedReader. 
		BufferedReader inFromUser = new BufferedReader(new InputStreamReader(;
		// Create and initialized the TCP connection between client and server.
		// DNS looks up on the host name and the port number is the same at the
		// server side application
		Socket clientSocket = new Socket("yourhost", 6789);
		// Create a stream object to attached to the socket. OutToServer stream
		// processes the output to server
		DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
		// The inFromServer stream provide the process input from the socket
		BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
		// Reads a line of text typed by user
		sentence = inFromUser.readLine();
		// The sentence sent through the client's socket and into the TCP pipe,
		// then wait for receiving characters from server.
		outToServer.writeBytes(sentence + '\n');
		// Characters arriving from server flow through the stream and placed
		// into modifySenctence
		modifySentence = inFromServer.readLine();
		// Print out modifySentence to console
		System.out.println("FROM SERVER:" + modifySentence);
		// Close TCP connection b/w the client and server

public class TCPServer {
	public static void main(String[] args) throws Exception {
		String clientSentence;
		String respondedSentence;
		// Create and initialize ServerSocket called welcomeSocket that listen
		// at 6789 port.
		ServerSocket welcomeSocket = new ServerSocket(6789);
		while (true) {
			// Create connectionSocket at server that allow the client and
			// server to send bytes to each other.
			Socket connectionSocket = welcomeSocket.accept();
			BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
			DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
			// Read bytes from the client
			clientSentence = inFromClient.readLine();
			// Mainly process of the application. Count number of characters of
			// the client
			respondedSentence = String.valueOf(clientSentence.length()) + '\n';
			// Send the respondedSentence to the client

UDP Implementation

UDP socket diagram

Figure 3: The client-server application using UDP.

public class UDPClient {
	public static void main(String[] args) throws Exception {
		BufferedReader inFromUser = new BufferedReader(new InputStreamReader(;
		// DatagramSocket does not take host/port argument like TCP because of
		// only creating a door for client process instead of a pipe between the
		// two processes
		DatagramSocket clientSocket = new DatagramSocket();
		// DNS looks up IPAddress of the destination host
		InetAddress ipAddress = InetAddress.getByName("yourhost");
		// Create bytes arrays that hold the data client sends and receives
		byte[] sendData = new byte[1024];
		byte[] receiveData = new byte[1024];
		String sentence = inFromUser.readLine();
		sendData = sentence.getBytes();
		// The client will pop sendPacket into the network thanks to its socket;
		// ipAddress and port of the server attached as well.
		DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, ipAddress, 9999);
		// TCP inserts the data into stream, whereas the UDP send and then wait from the server
		// Create a receivedPacket where places the data receiving from the server
		DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
		// Extract data from receivePacket and convert it to string modifiedSentence 
		String modifiedSentence = new String(receivePacket.getData());
		// Display it to console output
		System.out.println("FROM SERVER:" + modifiedSentence);
		// Close client socket

public class UDPServer {
	public static void main(String[] args) throws Exception {
		// All data sent and received, from single or multiple clients will pass
		// through this socket "door"
		DatagramSocket serverSocket = new DatagramSocket(9999);
		byte[] receiveData = new byte[1024];
		byte[] sendData = new byte[1024];
		while (true) {
			DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
			// Extract data from the client's packet and places in the String
			String sentence = new String(receivePacket.getData());
			// Get the client's IP address
			InetAddress ipAddress = receivePacket.getAddress();
			// Get the client's port number and is different from the server
			// port number 9999
			int port = receivePacket.getPort();
			// Process count characters of the sentence
			sentence = sentence.trim();		
			String respondedSentence = String.valueOf(sentence.length());
			// Transfer it to bytes
			sendData = respondedSentence.getBytes();
			// The server must know the IPAdress and port number of the client
			// in order to send back the data to client
			DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, ipAddress, port);


  • James F.Kurose, and Keith W.Ross, “Application Layer”, In Computer Networking: A Top-Down Approach, Chapter 2, pp. 160-178, Pearson, 5th edition, 2010.
  • Leave a Reply

    Your email address will not be published. Required fields are marked *