Network Programming - UDP and TCP in Java

·

3 min read

What's network programming? Shortly, it's a program running on multiple devices over the internet to help send and receive the data.

This article is mainly used for self-learning and practice. Hope it is helpful and clear for beginners!

Terminologies

  • IP Address: a unique address of each device on the internet. E.g., IPv4 and IPv6.
  • Port: Each device may have a lot of programs running at the same time. To distinguish these programs, each program binds with one port number over the communication.
  • Protocols: this is the rule to define how we communicate with each other over the internet. Basically, we have UDP and TCP.

UDP vs TCP

In short, UDP is more efficient than TCP because it doesn't check the connection, and also doesn't care about the data integrity. While TCP is safer than UDP as it will check connection status between both the client and the server.

UDP Code

Send

import java.io.IOException;
import java.net.*;

public class clientDemo {

    public static void main(String[] args) throws IOException {
        // Create socket object (DatagramSocket)
        DatagramSocket ds = new DatagramSocket();

        // Create data packet
        byte[] data = "Hello world!".getBytes();
        DatagramPacket dp = new DatagramPacket(data, data.length, InetAddress.getByName("192.168.1.66"), 10002);

        // Send data to server
        ds.send(dp);

        // Close socket
        ds.close();
    }
}

Receive

  • Create a socket object by DatagramSocket.
  • Construct data packet using DatagramPacket to receive the data.
  • Parse the data we received and print it in the console.
  • Close socket.
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class ServerDemo {
    public static void main(String[] args) throws IOException {
        // Create a socket object for receiver
        DatagramSocket ds = new DatagramSocket(10002);

        // Construct a data packet to receive the data
        byte[] data = new byte[1024];
        DatagramPacket dp = new DatagramPacket(data, data.length);

        // Receive data
        ds.receive(dp);

        // Parse the data we received and print it out
        byte[] receivedData = dp.getData();
        int receivedLen = dp.getLength();
        System.out.println("Received data: " + new String(receivedData, 0, receivedLen));

        // Close socket
        ds.close();
    }
}

TCP Code

Compared with UDP, TCP will check connections between sender and receiver. So, we need to make sure that the receiver is listening to a certain port before sending the data from the sender.

Receive

  • Create a socket object for the server by ServerSocket.
  • Listen to a port and accept the socket from the client.
  • Get the InputStream and print it out.
  • Close sockets.
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerDemo {
    public static void main(String[] args) throws IOException {
        // Create a socket object for receiver
        ServerSocket ds = new ServerSocket(10002);

        // Listen to port 10002 and get the socket
        Socket socket = ds.accept();

        // Get input stream and parse the data
        InputStream is = socket.getInputStream();
        byte[] data = new byte[1024];
        int len = is.read();
        System.out.println("Received data: " + new String(data, 0, len));

        // Close socket
        socket.close();
        ds.close();
    }
}

Send

We must make sure that the server-side is listening to the same port as we send data, otherwise, you would get a connect error.

import java.io.IOException;
import java.io.OutputStream;
import java.net.*;

public class clientDemo {

    public static void main(String[] args) throws IOException {
        // Create socket object (Socket)
        Socket socket = new Socket("192.168.1.66", 10002);

        // Get output stream and send data
        OutputStream os = socket.getOutputStream();
        os.write("Hello, TCP!".getBytes());

        // Close socket
        socket.close();
    }
}

Cheers!