SocketChannel Creation
In this chapter you will learn:
Create SocketChannel from IP address
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.nio.channels.SocketChannel;
//j a v a 2 s. c o m
public class MainClass {
public static void main(String[] args) throws Exception {
int port = 1919;
SocketAddress address = new InetSocketAddress("127.0.0.1", port);
SocketChannel client = SocketChannel.open(address);
ByteBuffer buffer = ByteBuffer.allocate(4);
IntBuffer view = buffer.asIntBuffer();
for (int expected = 0;; expected++) {
client.read(buffer);
int actual = view.get();
buffer.clear();
view.rewind();
if (actual != expected) {
System.err.println("Expected " + expected + "; was " + actual);
break;
}
System.out.println(actual);
}
}
}
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » Socket