Creating a Simple Java UDP Server and Client Socket

In this post, it is shown how a simple Java UDP server and client socket application can be implemented. For this example, Java SE 8 and the Eclipse Neon IDE setup described in the post below was used.

The Java APIs for socket programming are part of the Java SE (Standard Edition). See java.io and java.net.

Related Posts

Summary

  1. Implementation of UDP Server Socket in Java
  2. Implementation of UDP Client Socket in Java
  3. Running the Java UDP Server and Client Socket
  4. Monitoring UDP Network Traffic with Wireshark

1  Implementation of UDP Server Socket in Java

  • Below is the Java source code for the UDP server socket implementation. It opens a UDP socket connection and listens to messages from clients on a given port.
  • The server socket is created in line 16. See java.net.DatagramSocket for more information.
package com.pgx.java.socket;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class UDPServer {

    private DatagramSocket udpSocket;
    private int port;
 
    public UDPServer(int port) throws SocketException, IOException {
        this.port = port;
        this.udpSocket = new DatagramSocket(this.port);
    }

    private void listen() throws Exception {
        System.out.println("-- Running Server at " + InetAddress.getLocalHost() + "--");
        String msg;
        
        while (true) {
            
            byte[] buf = new byte[256];
            DatagramPacket packet = new DatagramPacket(buf, buf.length);
            
            // blocks until a packet is received
            udpSocket.receive(packet);
            msg = new String(packet.getData()).trim();
            
            System.out.println(
                "Message from " + packet.getAddress().getHostAddress() + ": " + msg);
        }
    }
    
    public static void main(String[] args) throws Exception {
        UDPServer client = new UDPServer(Integer.parseInt(args[0]));
        client.listen();
    }
}
  • The DatagramSocket.receive(DatagramPacket p) method, called in line 28, blocks until data is available to read from the socket connection. The data read from the socket is stored in a DatagramPacket object.
  • The main method in this class requires a port number as an input argument.

2  Implementation of UDP Client Socket in Java

  • Below is the Java source code for the UDP client socket implementation. It connects to a listening UDP socket using a given port and then sends console input to the server.
package com.pgx.java.socket;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;

public class UDPClient {

    private DatagramSocket udpSocket;
    private InetAddress serverAddress;
    private int port;
    private Scanner scanner;

    private UDPClient(String destinationAddr, int port) throws IOException {
        this.serverAddress = InetAddress.getByName(destinationAddr);
        this.port = port;
        udpSocket = new DatagramSocket(this.port);
        scanner = new Scanner(System.in);
    }

    public static void main(String[] args) throws NumberFormatException, IOException {        
        UDPClient sender = new UDPClient(args[0], Integer.parseInt(args[1]));
        System.out.println("-- Running UDP Client at " + InetAddress.getLocalHost() + " --");
        sender.start();
    }

    private int start() throws IOException {
        String in;

        while (true) {
            in = scanner.nextLine();
            
            DatagramPacket p = new DatagramPacket(
                in.getBytes(), in.getBytes().length, serverAddress, port);
            
            this.udpSocket.send(p);                    
        }
    }
}
  • In line 35, the client uses the DatagramSocket.send(DatagramPacket p) method to send a UDP message to the server.
  • The main method requires the hostname or IP address and the port number as input arguments.

3  Running the Java UDP Server and Client Socket

  • Here, the Java UDP server and client socket application is exported to an executable JAR file named UDPSocketTest.jar. For a quick description on how to create a JAR file in Eclipse, see:
  • The JAR file can be copied to a remote machine on the network using the below command:
  cat UDPSocketTest.jar | ssh root@192.168.56.10 'cat -> UDPSocketTest.jar'
  • Here, the server and client socket will run on different machines in a 192.168.56.* local network.

3.1 Start the Server

  • To run the server socket from a terminal or Windows command prompt, use the java command:
  java -cp UDPSocketTest.jar com.pgx.java.socket.UDPServer 7077
  • Where the only input argument is the port number, here 7077.

MyMac:java admin$ ls
UDPSocketTest.jar

MyMac:java admin$ java -cp UDPSocketTest.jar com.pgx.java.socket.UDPServer 7077

-- Running Server at MyMac/192.168.56.1 --
 

3.2 Start the Client

  • To run the client from a terminal or Windows command prompt, use the java command:
  java -cp UDPSocketTest.jar com.pgx.java.socket.UDPClient 192.168.56.1 7077
  • Where the first input argument is the host name and the second one is the port number.

[root@vapp ~]# ls
UDPSocketTest.jar

[root@vapp ~]# java -cp UDPSocketTest.jar com.pgx.java.socket.UDPClient 192.168.56.1 7077

-- Running UDP Client at vapp/192.168.0.15 --

3.3 Send a Message

  • In the client socket application, type a message and press ENTER.

[root@vapp ~]# java -cp UDPSocketTest.jar com.pgx.java.socket.UDPClient 192.168.56.1 7077

-- Running UDP Client --
Hello from the client!

  • The server socket application, will simply print the message from the client.

MyMac:java admin$ java -cp UDPSocketTest.jar com.pgx.java.socket.UDPServer 7077

-- Running Server at MyMac/192.168.56.1 --
Message from 192.168.56.10: Hello from the client!

  • Use CTRL + C to stop the both Java applications.

4  Monitoring UDP Network Traffic with Wireshark

Wireshark Download Page - Download Stable Release for Mac OS 10.6 and Later
  • After installation, run Wireshark and select a network interface to capture traffic on.
  • Here, the UDP socket client is running on Ubuntu hosted on a virtual machine using Oracle VirtualBox.
  • The virtual machine and the host machine use a host-only network called vboxnet0 to communicate.
Wireshark - Select Network Interface for UDP Server and Client Socket Traffic Capture
  • In the green filter field, enter the below pattern to filter the traffic by the selected UDP socket port:
udp.port == 7077
  • Send messages from the client- to the server socket to capture traffic.
  • To view the payload of a UDP packet, expand the Data node and click on the [Length: ..] item.
Wireshark - Capturing Java UDP Server and Client Socket Traffic on VBOXNET0 Interface

2 thoughts on “Creating a Simple Java UDP Server and Client Socket

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.