Socket Programming – UDP

DatagramClient

import java.io.*;

import java.net.*;

class datagramclient

{

public static DatagramSocket ds;

public static byte buffer[]= new byte[1024];

public static int clientport = 789, serverport = 790;

public static void main(String args[]) throws Exception

{

ds=new DatagramSocket(serverport);

System.out.println(“Server is waiting…”);

//System.out.println(“Press ctrl+c to quit the program”);

BufferedReader dis = new BufferedReader(new

InputStreamReader(System.in));

InetAddress ia = InetAddress.getByName(“127.0.0.1”);

while(true)

{

String str = dis.readLine();

if(str.equals(“end”))

break;

buffer = str.getBytes();

ds.send(new DatagramPacket(buffer, str.length(), ia, clientport));

DatagramPacket p = new DatagramPacket(buffer, buffer.length);

ds.receive(p);

String psx = new String(p.getData(), 0, p.getLength());

System.out.println(psx);

}

}

}

Datagram Server

import java.io.*;

import java.net.*;

class datagramserver

{

public static DatagramSocket ds;

public static byte buffer[]= new byte[1024];

public static int clientport = 789, serverport = 790;

public static void main(String args[]) throws Exception

{

ds=new DatagramSocket(clientport);

System.out.println(“Client is waiting…”);

System.out.println(“Press ctrl+c to quit the program”);

BufferedReader dis = new BufferedReader(new

InputStreamReader(System.in));

InetAddress ia = InetAddress.getByName(“127.0.0.1”);

while(true)

{

DatagramPacket p = new DatagramPacket(buffer, buffer.length);

ds.receive(p);

String psx = new String(p.getData(), 0, p.getLength());

System.out.println(psx);

String str = dis.readLine();

if(str.equals(“end”))

break;

buffer = str.getBytes();

ds.send(new DatagramPacket(buffer, str.length(), ia, serverport));

}

}

}

Advertisements