Full width home advertisement

Electronics Hub

Internet of Networks

Post Page Advertisement [Top]

Q. Write a Java program to implement chat server by using UDP Socket.

Ans.

Server side program:

import java.io.*; 
import java.net.*; 
class udpchatserver 

public static int clientport = 8040,serverport = 8050; 
public static void main(String args[]) throws Exception 

DatagramSocket SrvSoc = new DatagramSocket(clientport); 
byte[] SData = new byte[1024]; 
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
System.out.println("Server Ready"); 
while (true) 

byte[] RData = new byte[1024]; 
DatagramPacket RPack = new DatagramPacket(RData,RData.length); 
SrvSoc.receive(RPack); 
String Text = new String(RPack.getData()); 
if (Text.trim().length() == 0) 
break; 
System.out.println("\nFrom Client <<< " + Text ); 
System.out.print("Msg to Client : " ); 
String srvmsg = br.readLine(); 
InetAddress IPAddr = RPack.getAddress(); 
SData = srvmsg.getBytes(); 
DatagramPacket SPack = new DatagramPacket(SData,SData.length,IPAddr,
serverport); 
SrvSoc.send(SPack); 

System.out.println("\nClient Quits\n"); 
SrvSoc.close();
}
}
  

Client side program:

import java.io.*; 
import java.net.*; 
class udpchatclient 

public static int clientport = 8040, serverport = 8050; 
public static void main(String args[]) throws Exception

BufferedReader br = new BufferedReader(new InputStreamReader (System.in)); 
DatagramSocket CliSoc = new DatagramSocket(serverport); 
InetAddress IPAddr; 
String Text; 
if (args.length == 0) 
IPAddr = InetAddress.getLocalHost(); 
else 
IPAddr = InetAddress.getByName(args[0]); 
byte[] SData = new byte[1024]; 
System.out.println("Press Enter without text to quit"); 
while (true) 

System.out.print("\nEnter text for server : "); 
Text = br.readLine(); 
SData = Text.getBytes(); 
DatagramPacket SPack = new DatagramPacket(SData,SData.length, IPAddr,
clientport ); 
CliSoc.send(SPack); 
if (Text.trim().length() == 0) 
break; 
byte[] RData = new byte[1024];
DatagramPacket RPack = new DatagramPacket(RData,RData.length); 
CliSoc.receive(RPack); 
String Echo = new String(RPack.getData()) ; 
Echo = Echo.trim(); 
System.out.println("From Server <<< " + Echo); 

CliSoc.close(); 

}

First execute server side program,

Output:

javac udpchatserver.java (//enter)
java udpchatserver (//enter)
Server Ready

Then execute client side program,

Output:

javac udpchatclient.java (//enter) 
java udpchatclient (//enter)
Press Enter without text to quit
Enter text to server:
How are you?


javac udpchatserver.java (//enter)
java udpchatserver (//enter)
Server Ready
From client <<< How are you?
Msg to client
Fine

java udpchatclient (//enter)
From Server <<< Fine

chat bot, chat room
Free picture downloaded from unsplash.com

1 comment:

Bottom Ad [Post Page]

| Designed by Sriparna Sarkar