Java examples for Network:Datagram Channel
A Client Program Based on the Datagram Channel
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 = DatagramChannel.open(); client.bind(null);//from ww w. j av a 2s. com 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(); } }