Create a ByteBuffer for Socket communication with SocketChannel in Java

Description

The following code shows how to create a ByteBuffer for Socket communication with SocketChannel.

Example


//  w w w  .ja  va2  s . c o  m

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.SocketChannel;
import java.nio.channels.WritableByteChannel;

public class Main {

  public static void main(String[] args) throws Exception {
    int port = 19;

    SocketAddress address = new InetSocketAddress("127.0.0.1", port);
    SocketChannel client = SocketChannel.open(address);

    ByteBuffer buffer = ByteBuffer.allocate(74);
    WritableByteChannel out = Channels.newChannel(System.out);

    while (client.read(buffer) != -1) {
      buffer.flip();
      out.write(buffer);
      buffer.clear();
    }
  }
}




















Home »
  Java Tutorial »
    Network »




NetworkInterface
URI
URL
HTTP
HTTP Read
IP
Socket
UDP
URL Encode