Welcome to the World of Programming

Welcome to the World of Programming

Search this blog

Server-Client Chat Program using UDP Packets

Server Side Code :

import java.net.*;
import java.io.*;

class UDPServer{
    public static void main(String args[])throws IOException{
        DatagramSocket ds=new DatagramSocket(1234);
        byte buf[]=new byte[1024];
        DatagramPacket dp=new DatagramPacket(buf,buf.length);
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        InetAddress ia=InetAddress.getLocalHost();
        System.out.println("Server is Starting....");
        while(true){
            ds.receive(dp);
            String str=new String(dp.getData(),0,dp.getLength());
            if(str.equals("exit")){
                System.out.println("Terminated...");
                break;
            }
            System.out.println("Client : "+str);
            String str1=new String(br.readLine());
            buf=str1.getBytes();
            ds.send(new DatagramPacket(buf,str1.length(),ia,1235));
        }
    }
}

Client Side Code :

import java.net.*;
import java.io.*;

class UDPClient{
    public static void main(String args[])throws Exception{
        DatagramSocket ds=new DatagramSocket(1235);
        byte buf[]=new byte[1024];
        DatagramPacket dp=new DatagramPacket(buf,buf.length);
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        InetAddress ia=InetAddress.getLocalHost();
        System.out.println("Client is Running....");
        while(true){
            String str=new String(br.readLine());
            buf=str.getBytes();
            if(str.equals("exit")){
                System.out.println("Terminated...");
                ds.send(new DatagramPacket(buf,str.length(),ia,1234));
                break;
            }
            ds.send(new DatagramPacket(buf,str.length(),ia,1234));
            ds.receive(dp);
            String str1=new String(dp.getData(),0,dp.getLength());
            System.out.println("Server : "+str1);
        }
    }
}

No comments:

Post a Comment