Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;

public class Main {
    public static void main(String[] args) throws Exception {
        DatagramChannel client = null;
        client = DatagramChannel.open();

        client.bind(null);

        String msg = "Hello";
        ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
        InetSocketAddress serverAddress = new InetSocketAddress("localhost", 8989);

        client.send(buffer, serverAddress);
        buffer.clear();
        client.receive(buffer);
        buffer.flip();
        int limits = buffer.limit();
        byte bytes[] = new byte[limits];
        buffer.get(bytes, 0, limits);
        String response = new String(bytes);
        System.out.println("Server  responded: " + response);
        client.close();
    }
}