Read and write with SocketChannel
In this chapter you will learn:
Reading from a SocketChannel
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
/* j ava 2s . c o m*/
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();
}
}
}
Writing to a SocketChannel
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
/*from j a v a2 s.c om*/
public class Main {
public static void main(String[] argv) throws Exception {
SocketChannel sChannel = SocketChannel.open();
sChannel.configureBlocking(false);
sChannel.connect(new InetSocketAddress("hostName", 12345));
ByteBuffer buf = ByteBuffer.allocateDirect(1024);
buf.put((byte) 0xFF);
buf.flip();
int numBytesWritten = sChannel.write(buf);
}
}
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » Socket