Advertisement
ldmohan

UDP Client

Feb 22nd, 2020
438
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.11 KB | None | 0 0
  1. import java.net.DatagramPacket;
  2. import java.net.DatagramSocket;
  3. import java.net.InetAddress;
  4. import java.net.InetSocketAddress;
  5. import java.net.SocketException;
  6.  
  7. public class UdpClient {
  8.    
  9.     public static void main(String args[]) {
  10.        
  11.          
  12.          
  13.      
  14.          byte[] buf;
  15.          byte[] buf2 = new byte[1024];
  16.        
  17.          
  18.         InetSocketAddress address= new InetSocketAddress("127.0.0.1",9999);
  19.          
  20.          try {
  21.             DatagramSocket client= new  DatagramSocket();
  22.            
  23.             String msg=" --Your name goes here-- ";
  24.              buf = msg.getBytes();
  25.                 DatagramPacket packet = new DatagramPacket(buf, buf.length, address);
  26.                 client.send(packet);
  27.                
  28.                 DatagramPacket packet2 = new DatagramPacket(buf2, buf2.length);
  29.                 client.receive(packet2);
  30.                 String received = new String(
  31.                   packet2.getData(), 0, packet2.getLength());
  32.                
  33.                
  34.                 System.out.println("Receive msg "+ received+"from "+packet2.getSocketAddress());
  35.                 client.close();
  36.            
  37.         } catch (Exception e) {
  38.             // TODO Auto-generated catch block
  39.             e.printStackTrace();
  40.         }
  41.     }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement