DatagramChannel Receive Example

This program demonstrates receiving UDP packets using DatagramChannel.

Problem Statement

Write a Java program that receives data using DatagramChannel.

Source Code

1 import java.net.*;
2 import java.nio.*;
3 import java.nio.channels.*;
4 public class DatagramChannelReceiveExample {
5 public static void main(String[] args) throws Exception {
6 System.out.println("Eduinq DatagramChannel Receive Example");
7 DatagramChannel dc=DatagramChannel.open();
8 dc.bind(new InetSocketAddress(6000));
9 ByteBuffer buffer=ByteBuffer.allocate(1024);
10 dc.receive(buffer);
11 buffer.flip();
12 while(buffer.hasRemaining()){ System.out.print((char)buffer.get()); }
13 dc.close();
14 }
15 }

Program Output

					Eduinq DatagramChannel Receive Example
Eduinq UDP Message
				

Explanation

Uses DatagramChannel.receive() for UDP. - Binds to port for listening. - Exception handling ensures safe operations. - In enterprise systems, DatagramChannel supports message reception. Conclusion: Shows receiving with DatagramChannel.

Quick Links to Explore