Reading from a SocketChannel : NIO Socket « Network Protocol « Java






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();
    }
  }
}

   
  








Related examples in the same category

1.Non block server
2.Finger Server
3.Writing to a SocketChannel
4.Creating a Non-Blocking Server Socket
5.Creating a Non-Blocking Socket: requires a socket channel.
6.Accepting a Connection on a ServerSocketChannel
7.Using a Selector to Manage Non-Blocking Server Sockets