Java DatagramSocket create UDP server

Description

Java DatagramSocket create UDP server

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[10], sbuf = new byte[10];
      // create a server socket at port 5000
      DatagramSocket socket = new DatagramSocket(5000);
      System.out.println("Server ready");
      DatagramPacket rpkt = new DatagramPacket(rbuf, rbuf.length);
      // receive a packet from client
      socket.receive(rpkt);//from www.j a v a 2 s  . c  o  m
      // extract data and client information from this packet
      String data = new String(rpkt.getData(), 0, rpkt.getLength());
      InetAddress addr = rpkt.getAddress();
      int port = rpkt.getPort();
      int fact = 1, n = Integer.parseInt(data);
      System.out.println("Received: " + n + " from " + addr + ":" + port);
      for (int i = 2; i <= n; i++)
         fact *= i;
      sbuf = String.valueOf(fact).getBytes();
      DatagramPacket spkt = new DatagramPacket(sbuf, sbuf.length, addr, port);
      // send result to the client
      socket.send(spkt);
      System.out.println("Sent: " + fact);

   }
}



PreviousNext

Related