DatagramChannel Send Example
This program demonstrates sending UDP packets using DatagramChannel.
Problem Statement
Write a Java program that sends data using DatagramChannel.
Source Code
| 1 | import java.net.*; |
| 2 | import java.nio.*; |
| 3 | import java.nio.channels.*; |
| 4 | public class DatagramChannelSendExample { |
| 5 | public static void main(String[] args) throws Exception { |
| 6 | System.out.println("Eduinq DatagramChannel Send Example"); |
| 7 | DatagramChannel dc=DatagramChannel.open(); |
| 8 | ByteBuffer buffer=ByteBuffer.wrap("Eduinq UDP Message".getBytes()); |
| 9 | dc.send(buffer,new InetSocketAddress("localhost",6000)); |
| 10 | dc.close(); |
| 11 | System.out.println("Eduinq Datagram Sent Successfully"); |
| 12 | } |
| 13 | } |
Program Output
Eduinq DatagramChannel Send Example Eduinq Datagram Sent Successfully
Explanation
Uses DatagramChannel.send() for UDP. - Sends message to target address. - Exception handling ensures safe operations. - In enterprise systems, DatagramChannel supports lightweight communication. Conclusion: Shows sending with DatagramChannel.