30 Ağustos 2023 Çarşamba

DatagramChannel Sınıfı - NIO UDP Sunucusu

constructor
Örnek
Şöyle yaparız
// Create a DatagramSocket
DatagramSocket socket = new DatagramSocket(9999);

// Receive a datagram packet
DatagramPacket packet = new DatagramPacket(new byte[1024], 1024);
socket.receive(packet);

// Get the data from the packet
String data = new String(packet.getData(), 0, packet.getLength());

// Send a reply
String reply = "Hello, world!";
DatagramPacket replyPacket = new DatagramPacket(
  reply.getBytes(), 
  reply.length(), 
  packet.getAddress(), 
  packet.getPort());

socket.send(replyPacket);
bind metodu
Örnek
Şöyle yaparız
int port = 12345; // Change this to the desired port number
DatagramChannel channel = DatagramChannel.open(); channel.bind(new InetSocketAddress(port)); System.out.println("Server listening on port " + port); ByteBuffer buffer = ByteBuffer.allocate(1024); while (true) { buffer.clear(); InetSocketAddress clientAddress = (InetSocketAddress) channel.receive(buffer); buffer.flip(); // prepare for reading after data has been written into it System.out.println("Received message from " + clientAddress.getAddress() + ":" + clientAddress.getPort()); // Process the received data (here we're just echoing it back) channel.send(buffer, clientAddress);

Hiç yorum yok:

Yorum Gönder