UDP Server and Client in Java

Submitted by Karthikeyan on

Simple UDP server and client program in Java.
In this program Server sends message to client.
First, run the Client and then run the server.

UDP Server

Message can be sent to any system in LAN.
If you wish to do, Uncomment the 9th line and change the the 'mypc' to destination pc name, then remove the 8th line.


import java.net.*;
import java.io.*;
import java.util.*;
public class udpserver {
    public static void main(String args[])throws Exception
    {
        DatagramSocket dsoc = new DatagramSocket(5217);
        InetAddress host = InetAddress.getLocalHost();
        //InetAddress host = InetAddress.getByName("MYPC");
        String str="Hello! This msg is sent from UDP Server \n" +(new Date()).toString();
        byte buf[] = str.getBytes();
        dsoc.send(new DatagramPacket(buf,buf.length,host,27));           
        dsoc.close();
        }
    }

UDP Client


import java.net.*;
import java.io.*;
public class udpclient {
    public static void main(String args[]) throws Exception
{
DatagramSocket dsoc = new DatagramSocket(27);
byte buff[] = new byte[1023];
DatagramPacket dpack= new DatagramPacket(buff,buff.length);
dsoc.receive(dpack);
System.out.println(new String(dpack.getData()));
}
}