SocketChannel Read Example
This program demonstrates reading data from a server using SocketChannel.
Problem Statement
Write a Java program that reads data from a server using SocketChannel.
Source Code
| 1 | import java.net.*; |
| 2 | import java.nio.*; |
| 3 | import java.nio.channels.*; |
| 4 | public class SocketChannelReadExample { |
| 5 | public static void main(String[] args) throws Exception { |
| 6 | System.out.println("Eduinq SocketChannel Read Example"); |
| 7 | SocketChannel sc=SocketChannel.open(new InetSocketAddress("localhost",5000)); |
| 8 | ByteBuffer buffer=ByteBuffer.allocate(1024); |
| 9 | sc.read(buffer); |
| 10 | buffer.flip(); |
| 11 | while(buffer.hasRemaining()){ System.out.print((char)buffer.get()); } |
| 12 | sc.close(); |
| 13 | } |
| 14 | } |
Program Output
Eduinq SocketChannel Read Example Eduinq Response: Hello Eduinq
Explanation
Uses SocketChannel.read() with ByteBuffer. - Reads server response. - Exception handling ensures safe operations. - In enterprise systems, SocketChannel supports client server communication. Conclusion: Shows reading with SocketChannel.