Sureshjonna

CN 10 – CLIENT & SERVER PROGRAM USING UDP

10. Write a program on datagram socket for client/server to display the messages on client side, typed at the server side.

UDPServer.java – PROGRAM 

import java.net.*;
import java.util.Scanner;

public class UDPServer {
public static void main(String[] args) throws Exception{
Scanner in = new Scanner(System.in);
DatagramSocket socket=new DatagramSocket();
String msg=in.nextLine();

byte code[]=msg.getBytes();
InetAddress iAddress=InetAddress.getByName(“127.0.0.1”);
DatagramPacket request=new DatagramPacket(code,code.length,iAddress,4000);
socket.send(request);
}
}

UDPClient.java

import java.net.*;

public class UDPClient {
public static void main(String[] args) throws Exception{
DatagramSocket socket=new DatagramSocket(4000);
byte data[]=new byte[1000];

while(true) {
DatagramPacket request=new DatagramPacket(data, data.length);
socket.receive(request);
String str=new String(request.getData());
System.out.println(str);
}
}

}

OUTPUT :
( click on image to zoom )


Skip to toolbar