Java Sockets

UDP Sockets

import java.net.*;

public class DatagramExample {

  public static void main(String[] args) {
  
    String s = "This is a test.";
  
    byte[] data = s.getBytes();
    try {
      InetAddress ia = InetAddress.getByName("www.sc.edu");
      int port = 7;

      //create a packet.
      DatagramPacket dp 
        = new DatagramPacket(data, data.length, ia, port);
      System.out.println("This packet is addressed to " 
                         + dp.getAddress() + " on port " + dp.getPort());
      System.out.println("There are " + dp.getLength() 
                         + " bytes of data in the packet");
      System.out.println(
                         new String(dp.getData(), dp.getOffset(), dp.getLength()));
      //create a socket.
      DatagramSocket theSocket = new DatagramSocket();

      //send it.
      theSocket.send(dp);
  
    }
    catch (UnknownHostException e) {
      System.err.println(e);
    }
    
  }

}

import java.net.*;
import java.io.*;

public abstract class UDPServer extends Thread {

  private int bufferSize; // in bytes
  protected DatagramSocket ds;
   
  public UDPServer(int port, int bufferSize) 
    throws SocketException {
    this.bufferSize = bufferSize;
    ds = new DatagramSocket(port);
  }
  
  public UDPServer(int port) throws SocketException {
    //8192 is buffersize
    this(port, 8192);
  }
  
  public void run() {
  
    byte[] buffer = new byte[bufferSize];
    while (true) {
      DatagramPacket incoming = new DatagramPacket(buffer, buffer.length);
      try {
        ds.receive(incoming); //blocks for packet.
        respond(incoming);
      }
      catch (IOException e) {
        System.err.println(e);
      }      
    } // end while

  }  // end run
  
  public abstract void respond(DatagramPacket request);
  //implement this to answer back.

}


José M. Vidal .

9 of 9