Java DatagramSocket send number value to UDP server

Description

Java DatagramSocket send number value to UDP server

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]);
      while (true) {
         // get an integer from user
         System.out.print("Enter an integer: ");
         String data = fromUser.readLine();
         sbuf = data.getBytes();//  w w  w  .  jav a  2s. 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);
         if (data.equals("-1"))
            break;
         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