Java DatagramPacket create

Introduction

Create a packet to receive 1024 bytes of data

byte[] data = new byte[1024]; 
DatagramPacket packet = new DatagramPacket(data, data.length); 

Create a packet with buffer size of 1024, it will receive data starting at offset 8 and it will receive only 32 bytes of data.

byte[] data2 = new byte[1024]; 
DatagramPacket packet2 = new DatagramPacket(data2, 8, 32); 

Create a packet to send 1024 bytes of data that has a destination address of "localhost" and port 15900.

Need to populate data3 array before sending the packet.

byte[] data3 = new byte[1024];     
DatagramPacket packet3 = new DatagramPacket(data3, 1024,                      
                            InetAddress.getByName("localhost"), 15900); 

Create a packet to send 1024 bytes of data that has a destination address of "localhost" and port 15900.

byte[] data4 = new byte[1024];     
DatagramPacket packet4 = new DatagramPacket(data4, 1024); 
packet4.setAddress(InetAddress.getByName("localhost")); 
packet4.setPort(15900); 

An Echo Client Based on UDP Sockets

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class Main {
  public static void main(String[] args) {
    DatagramSocket udpSocket = null;
    try {//ww  w  . j  a  v  a  2 s. c om
      // Create a UDP socket at local host using an available port
      udpSocket = new DatagramSocket();

      String msg = null;
      // Create a buffered reader to get an input from a user
      BufferedReader  br = new BufferedReader(new InputStreamReader(System.in));
      String promptMsg = "Please enter a message (Bye to quit):";
      System.out.print(promptMsg);

      while ((msg = br.readLine()) != null) {
        if (msg.equalsIgnoreCase("bye")) {
          break;
        }
        // Prepare a packet to send to the server
        DatagramPacket packet = getPacket(msg);
        // Send the packet to the server
        udpSocket.send(packet);

        // Wait for a packet from the server
        udpSocket.receive(packet);
        // Display the packet details received from the server
        displayPacketDetails(packet);

        System.out.print(promptMsg);
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      // Close the socket
      if (udpSocket != null) {
        udpSocket.close();
      }
    }
  }

  public static void displayPacketDetails(DatagramPacket packet) {
    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("[Server IP=" + remoteAddr + ", port=" + remotePort + "]: " + msg);

    System.out.println();
  }

  public static DatagramPacket getPacket(String msg) throws UnknownHostException {
    final int PACKET_MAX_LENGTH = 1024;
    byte[] msgBuffer = msg.getBytes();

    int length = msgBuffer.length;
    if (length > PACKET_MAX_LENGTH) {
      length = PACKET_MAX_LENGTH;
    }

    DatagramPacket packet = new DatagramPacket(msgBuffer, length);

    int serverPort = 15900;
    final String SERVER_NAME = "localhost";
    InetAddress serverIPAddress = InetAddress.getByName(SERVER_NAME);
    packet.setAddress(serverIPAddress);
    packet.setPort(serverPort);

    return packet;
  }
}



PreviousNext

Related