SocketChannel Connect Example
This program demonstrates connecting to a server using SocketChannel.
Problem Statement
Write a Java program that connects to a server using SocketChannel and sends data.
Source Code
| 1 | import java.net.*; |
| 2 | import java.nio.*; |
| 3 | import java.nio.channels.*; |
| 4 | public class SocketChannelConnectExample { |
| 5 | public static void main(String[] args) throws Exception { |
| 6 | System.out.println("Eduinq SocketChannel Connect Example"); |
| 7 | SocketChannel sc=SocketChannel.open(new InetSocketAddress("localhost",5000)); |
| 8 | sc.write(ByteBuffer.wrap("Eduinq Message".getBytes())); |
| 9 | sc.close(); |
| 10 | System.out.println("Eduinq Data Sent Successfully"); |
| 11 | } |
| 12 | } |
Program Output
Eduinq SocketChannel Connect Example Eduinq Data Sent Successfully
Explanation
Uses SocketChannel.open() to connect. - Sends data using ByteBuffer. - Exception handling ensures safe operations. - In enterprise systems, SocketChannel supports non blocking networking. Conclusion: Shows connecting with SocketChannel.