Mega Code Archive

 
Categories / Java / Network Protocol
 

Reading from a SocketChannel

import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; public class Main {   public static void main(String[] argv) throws Exception {     ByteBuffer buf = ByteBuffer.allocateDirect(1024);     SocketChannel sChannel = SocketChannel.open();     sChannel.configureBlocking(false);     sChannel.connect(new InetSocketAddress("hostName", 12345));     int numBytesRead = sChannel.read(buf);     if (numBytesRead == -1) {       sChannel.close();     } else {       buf.flip();     }   } }