Tips & Tricks for Technologists & System Administrators | About & Contact

A Simple Java UDP Server and UDP Client


Posted 17th September in Code Samples, Java, Software. 44 Comments

For a class I am taking, we are testing out a simple UDP Server and UDP Client to demonstrate what each one does and how sockets work. The code size is very small and give you a good idea about how a UDP Server opens up a port, and then the UDP Client sends or receives data from that port.

To compile these, install Java JDK to your system. Then compile the program with javac UDPClient.java – this will create a UDPClient.class. Execute the file with java UDPClass – leave off the .class, or you will get the error: “Exception in thread “main” java.lang.NoClassDefFoundError”.

Here is sample code for a simple Java UCP Server and Client, originally from Computer Networking: A Top Down Approach, by Kurose and Ross:

UDPServer.java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import java.io.*;
import java.net.*;

class UDPServer
{
   public static void main(String args[]) throws Exception
      {
         DatagramSocket serverSocket = new DatagramSocket(9876);
            byte[] receiveData = new byte[1024];
            byte[] sendData = new byte[1024];
            while(true)
               {
                  DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                  serverSocket.receive(receivePacket);
                  String sentence = new String( receivePacket.getData());
                  System.out.println("RECEIVED: " + sentence);
                  InetAddress IPAddress = receivePacket.getAddress();
                  int port = receivePacket.getPort();
                  String capitalizedSentence = sentence.toUpperCase();
                  sendData = capitalizedSentence.getBytes();
                  DatagramPacket sendPacket =
                  new DatagramPacket(sendData, sendData.length, IPAddress, port);
                  serverSocket.send(sendPacket);
               }
      }
}

UDPClient.java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import java.io.*;
import java.net.*;

class UDPClient
{
   public static void main(String args[]) throws Exception
   {
      BufferedReader inFromUser =
         new BufferedReader(new InputStreamReader(System.in));
      DatagramSocket clientSocket = new DatagramSocket();
      InetAddress IPAddress = InetAddress.getByName("localhost");
      byte[] sendData = new byte[1024];
      byte[] receiveData = new byte[1024];
      String sentence = inFromUser.readLine();
      sendData = sentence.getBytes();
      DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
      clientSocket.send(sendPacket);
      DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
      clientSocket.receive(receivePacket);
      String modifiedSentence = new String(receivePacket.getData());
      System.out.println("FROM SERVER:" + modifiedSentence);
      clientSocket.close();
   }
}

Originally posted 20080917 and last touched 20110422
Dave Drager+ is the Chief Technology Officer at XDA-Developers, where he keeps the server farm running efficiently for millions of visitors per day. He has written previously for the technology blogs Lifehacker and MakeUseOf.


  • Pingback: Dave Drager

  • Pingback: systemBash » A Simple Java TCP Server and TCP Client

  • jomai

    from the Computer Networking: A top Down Approach by Kurose

  • jomai

    from the Computer Networking: A top Down Approach by Kurose

  • terry

    how to execute

  • terry

    how to execute

  • jeya

    how to execute

  • jeya

    how to execute

  • Me

    > javac UDPClient.java UDPServer.java
    Open two command prompt windows and write in one:
    > java UDPServer
    and after this, write on another:
    > java UDPClient

  • Me

    > javac UDPClient.java UDPServer.java
    Open two command prompt windows and write in one:
    > java UDPServer
    and after this, write on another:
    > java UDPClient

  • edgar

    In the server, you would like to take into account the size of the received package:

    String sentence = new String(receivePacket.getData(), 0, receivePacket.getLength());

  • edgar

    In the server, you would like to take into account the size of the received package:

    String sentence = new String(receivePacket.getData(), 0, receivePacket.getLength());

  • Anonymous

    its nt working on two different computer…what should i do

  • Anonymous

    its nt working on two different computer…what should i do

  • Nitin Verma

    Client is sending the packets to localhost, use the IP Adress or name of the m/c you are running server on.

    InetAddress IPAddress = InetAddress.getByName(“localhost”);

  • Nitin Verma

    Client is sending the packets to localhost, use the IP Adress or name of the m/c you are running server on.

    InetAddress IPAddress = InetAddress.getByName(“localhost”);

  • Pingback: Matt Hollander

  • Craig

    How do you set the UDP port on which the server is listening?

  • Craig

    How do you set the UDP port on which the server is listening?

  • Craig

    Ok I found it. It’s 9876. Thanks

  • Craig

    Ok I found it. It’s 9876. Thanks

  • vivek

    Good prgram for passing string,number etc between client &server

  • vivek

    Good prgram for passing string,number etc between client &server

  • Pingback: Dave Drager

  • Vaibhav

    THANK U SO MUCH…its so much simple and easy to understand…bcoz of this i completed my project successfully…Secure TFTP with Multithreaded Server my project title…i used some code of this in my project…Again THANK U….

  • Vaibhav

    THANK U SO MUCH…its so much simple and easy to understand…bcoz of this i completed my project successfully…Secure TFTP with Multithreaded Server my project title…i used some code of this in my project…Again THANK U….

  • Revathi

    hi i want file transfer program using udp protocol in java

  • Revathi

    hi i want file transfer program using udp protocol in java

  • Pingback: train_boy

  • MYK007

    Hello, I am having a problem with the codes, I have try to run them, but when i enter a sentence, there is no output it just holds on. Can you tell me why?

  • Nezhad

    is there a difference between the performance of sockets written in C vs. Java?

  • http://davedrager.com Dave Drager

    I think this depends on who you talk to. At scale there might be some differences in how things are handled by the system, but for this small scale project there will be no noticable difference.

  • RichR

    This code works really well, on WinXP, and even works on an Insignia Infocast (Chumby). Thanks!

  • user

    how to run in cmd??
    can anyone tell please exactly whta to do?

  • user1

    can u tell please exactly what to do in cmd?

  • Brusasu

    go into the directory where u save the file,
    launch “javac UDPServer.java” and “javac UDPCliend.java” to compile the source file, when u see .class file then in cmd run “java UDPServer” and into another shell “Java UDPClient”. that’s all.

  • Mayank

    Thanks alot, It gives us the very simper view to learn other than typical.Ty

  • shubham patni

    Is it work for Android Mobile

  • rviera

    Yes, just create a UI with an EditText, TextView, and a Button. Then modified the UDPClient code to receive the user input from the EditText. Also change the IP address of the Server. Next, change the output of the message that you received from the Server to print it in the TextView.
    Thanks for the code… 

  • Ssankarraj_sethu

    how to execute

  • Sankar

    Hello, I am having a problem with the codes, I have try to run them, but when i enter a sentence, there is no output it just holds on. Can you tell me why?

  • Yash Save

    Hi This code does not work when the 2 computers are on different network. Do we have to use the Trustmanager, or are there any changes needs to be done on the fire wall?

  • Muhammad Adeel Malik

    Desktopupd>javac UDPServer.java
    Desktopupd>java UDPServer.java (java UDPServer or java UDPServer.class or  java UDPClass – )
    Error
    Can anyone tell me?
    Exception in thread “main” java.lang.NoClassDefFoundError: UDPServer/javaCaused by: java.lang.ClassNotFoundException: UDPServer.java        at java.net.URLClassLoader$1.run(Unknown Source)        at java.security.AccessController.doPrivileged(Native Method)        at java.net.URLClassLoader.findClass(Unknown Source)        at java.lang.ClassLoader.loadClass(Unknown Source)        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)        at java.lang.ClassLoader.loadClass(Unknown Source)Could not find the main class: UDPServer.java.  Program will exit.

  • Brusasu

    when you want to run a java before compile, remove .java in the end.
    So after “javac UDPServer.java” run “java UDPServer” and it will run properly.

    bye