Java DatagramSocket create UDP client

Description

Java DatagramSocket create UDP client

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class Main {
   public static void main(String args[]) throws Exception {
      byte[] rbuf = new byte[1024], sbuf = new byte[1024];
      BufferedReader fromUser = new BufferedReader(new InputStreamReader(System.in));
      DatagramSocket socket = new DatagramSocket();
      InetAddress addr = InetAddress.getByName(args[0]);
      // get an integer from user
      System.out.print("Enter an integer: ");
      String data = fromUser.readLine();
      sbuf = data.getBytes();//from   ww w  .j  a va 2  s . c o m
      DatagramPacket spkt = new DatagramPacket(sbuf, sbuf.length, addr, 5000);
      // send it to server
      socket.send(spkt);
      System.out.println("Sent to server: " + data);
      DatagramPacket rpkt = new DatagramPacket(rbuf, rbuf.length);
      // retrieve result
      socket.receive(rpkt);
      data = new String(rpkt.getData(), 0, rpkt.getLength());
      System.out.println("Received from server: " + data);
      // close the socket
      socket.close();
   }
}



PreviousNext

Related