An Echo Server Based on UDP Sockets - Java Network

Java examples for Network:UDP

Description

An Echo Server Based on UDP Sockets

Demo Code

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

public class Main {
  public static void main(String[] args) throws Exception {
    DatagramSocket udpSocket = new DatagramSocket(5555,
        InetAddress.getByName("localhost"));
    System.out.println("Created UDP server socket at "
        + udpSocket.getLocalSocketAddress() + "...");

    while (true) {
      System.out.println("Waiting for a UDP packet" + " to arrive...");
      DatagramPacket packet = new DatagramPacket(new byte[1024], 1024);
      udpSocket.receive(packet);/*  ww  w  .  j a  v a 2  s.  co m*/
      displayPacketDetails(packet);
      udpSocket.send(packet);
    }
  }

  public static void displayPacketDetails(DatagramPacket packet) {
    // Get the message
    byte[] msgBuffer = packet.getData();
    int length = packet.getLength();
    int offset = packet.getOffset();

    int remotePort = packet.getPort();
    InetAddress remoteAddr = packet.getAddress();
    String msg = new String(msgBuffer, offset, length);

    System.out.println("Received a packet:[IP Address=" + remoteAddr
        + ", port=" + remotePort + ", message=" + msg + "]");
  }
}

Result


Related Tutorials