Writing to a SocketChannel - Java Network

Java examples for Network:Socket Channel

Description

Writing to a SocketChannel

Demo Code

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class Main {
  public static void main(String[] args) {
    ByteBuffer buf = ByteBuffer.allocateDirect(1024);

    try {/*w w w. ja  v  a2s.  com*/
      buf.put((byte) 0xFF);

      // Prepare the buffer for reading by the socket
      buf.flip();
      SocketChannel socketChannel = null;
      
      // Write bytes
      int numBytesWritten = socketChannel.write(buf);
    } catch (IOException e) {
      // Connection may have been closed
    }
  }
}

Related Tutorials