PacketReceiver.java Source code

Java tutorial

Introduction

Here is the source code for PacketReceiver.java

Source

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

class PacketReceiver {
    public static void main(String[] args) throws Exception {
        byte[] buffer = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
        DatagramSocket socket = new DatagramSocket(5002);
        socket.receive(packet);
        System.out.println(packet.getSocketAddress());
        buffer = packet.getData();
        System.out.println(new String(buffer));
    }
}

class PacketSender {

    public static void main(String[] args) throws Exception {
        byte[] buffer = "data".getBytes();
        DatagramPacket packet = new DatagramPacket(buffer, buffer.length, new InetSocketAddress("localhost", 5002));
        DatagramSocket socket = new DatagramSocket(5003);
        socket.send(packet);
    }
}