Java Programming Using UDP [Sending Messages from Client to Server and vice versa]
This is the java program to send message from client to the server and vice versa using UDP,the messages are sent as datagrampackets,the packets are routed individually to the destination
UDP (User Datagram Protocol) is a communications protocol that offers a limited amount of service when messages are exchanged between computers in a network that uses the Internet Protocol (IP). UDP is an alternative to the Transmission Control Protocol (TCP) and, together with IP, is sometimes referred to as UDP/IP.
Java Client:
client.java
import java.io.*;
import java.net.*;
public class client
{
public static void main(String[] args) throws Exception
{
int port=Integer.parseInt(args[0]);
DatagramSocket ds=new DatagramSocket();
while(true){
DataInputStream inp=new DataInputStream(System.in);
String Message=inp.readLine();
byte[] send=new byte[1024];
byte[] rcv=new byte[1024];
send=Message.getBytes();
InetAddress ip=InetAddress.getByName("localhost");
DatagramPacket sp=new DatagramPacket(send,send.length,ip,port);
ds.send(sp);
DatagramPacket rp=new DatagramPacket(rcv,rcv.length);
ds.receive(rp);
String m=new String(rp.getData());
System.out.println(m);
}
}
}
Java Server:
server.java
import java.io.*;
import java.net.*;
public class server
{
public static void main(String[] args) throws Exception
{
int port;
DatagramSocket dp=new DatagramSocket(Integer.parseInt(args[0]));
while(true)
{
byte[] send=new byte[1024];
byte[] rcv=new byte[1024];
DatagramPacket rp=new DatagramPacket(rcv,rcv.length);
dp.receive(rp);
String r=new String(rp.getData());
System.out.println(r);
String msg;
DataInputStream inp=new DataInputStream(System.in);
msg=inp.readLine();
send=msg.getBytes();
InetAddress ip=rp.getAddress();
port=rp.getPort();
DatagramPacket sp=new DatagramPacket(send,send.length,ip,port);
dp.send(sp);
}
}
}
Recent Comments