2023 characters | 82 lines | 1.98 KB
DOWNLOAD | RAW | EMBED | CREATE NEW VERSION OF THIS PASTE | REPORT ABUSE | x
  1. //UDPCLIENT
  2.  
  3.  
  4. import java.io.*;
  5. import java.net.*;
  6. public class client
  7. {
  8.  public static void main(String args[])
  9.  {
  10.   try
  11.   {
  12.    DatagramSocket socket=new DatagramSocket();
  13.    byte [] buff=new byte[1024];
  14.    InetAddress address=InetAddress.getByName("localhost");
  15.    System.out.println("Trying...to connect to the server.");
  16.    while(true)
  17.    {
  18.     System.out.println("Enter data");
  19.     BufferedReader buff_data=new BufferedReader(new InputStreamReader(System.in));
  20.     String user_data=buff_data.readLine();
  21.     buff=user_data.getBytes();
  22.     DatagramPacket packet=new DatagramPacket(buff,buff.length,address,4455);
  23.     socket.send(packet);
  24.    }
  25.   }
  26.   catch(UnknownHostException unknown_host)
  27.   {
  28.    System.out.println("Unknown host..");
  29.    unknown_host.printStackTrace();
  30.   }
  31.   catch(SocketException socket_error)
  32.   {
  33.    System.out.println("Some socket error has occured.");
  34.    socket_error.printStackTrace();
  35.   }
  36.   catch(IOException input_error)
  37.   {
  38.    System.out.println("Some input error has occured.");
  39.    input_error.printStackTrace();
  40.   }
  41.  }
  42. }
  43.  
  44. //UDPSERVER
  45.  
  46. import java.net.DatagramPacket;
  47. import java.net.DatagramSocket;
  48. import java.io.IOException;
  49. import java.net.SocketException;
  50. public class server
  51. {
  52.  public static void main(String args[])
  53.  {
  54.   new server().chatting();
  55.  }
  56.  public void chatting()
  57.  {
  58.   try
  59.   {
  60.    DatagramSocket socket=new DatagramSocket(4455);
  61.    byte[] buff=new byte[1024];
  62.    while(true)
  63.    {
  64.     DatagramPacket packet=new DatagramPacket(buff,buff.length);
  65.     socket.receive(packet);
  66.     String client_packet=new String(packet.getData(),0,packet.getLength());
  67.     System.out.println("Received a packet from client "+client_packet);
  68.    }
  69.   }
  70.   catch(SocketException socket_error)
  71.   {
  72.    System.out.println("Socket exception has occured.");
  73.    socket_error.printStackTrace();
  74.   }
  75.   catch(IOException input_error)
  76.   {
  77.    System.out.println("Input error has occured.");
  78.    input_error.printStackTrace();
  79.   }
  80.  }
  81. }