Java DatagramSocket create UDP server with Thread

Description

Java DatagramSocket create UDP server with Thread

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class Main {
   public static void main(String args[]) throws Exception {
      // create a server socket at port 5000
      DatagramSocket socket = new DatagramSocket(5000);
      System.out.println("Server ready");
      while (true) {
         byte[] rbuf = new byte[10];
         DatagramPacket rpkt = new DatagramPacket(rbuf, rbuf.length);
         // receive a packet from client
         socket.receive(rpkt);// www .j a v a2s .  c o m
         System.out.println("Receiver a packet");
         // hand over this packet to Handler
         new Handler(rpkt, socket);
      }
   }
}

class Handler implements Runnable {
   DatagramSocket socket;
   DatagramPacket pkt;

   Handler(DatagramPacket pkt, DatagramSocket socket) {
      this.pkt = pkt;
      this.socket = socket;
      new Thread(this).start();
      System.out.println("A thread created");
   }

   public void run() {
      try {
         byte[] sbuf = new byte[10];
         // extract data and client information from this packet
         String data = new String(pkt.getData(), 0, pkt.getLength());
         InetAddress addr = pkt.getAddress();
         int port = pkt.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);
      } catch (IOException e) {
      }

   }
}



PreviousNext

Related