java游戏开发群:66728073
一,SocketChannel
(1)创建连接
SocketChannelsocketChannel = SocketChannel.open();
socketChannel.connect(newInetSocketAddress("http://jenkov.com", 80));
连接到一个服务器。
(2)从channel中读取信息
ByteBufferbuf = ByteBuffer.allocate(48);
intbytesRead = socketChannel.read(buf);
(3)写入到channel信息
String newData = "New String towrite to file..." + System.currentTimeMillis();
ByteBuffer buf =ByteBuffer.allocate(48);
buf.clear();
buf.put(newData.getBytes());
buf.flip();
while(buf.hasRemaining()){
channel.write(buf);
}
二,ServerSocketChannel
例如:
ServerSocketChannelserverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(newInetSocketAddress(9999));
//在这时设置阻塞或非阻塞,true阻塞模式,默认为false
serverSocketChannel.configureBlocking(false);
while(true){
//监听连接过来的连接
SocketChannel socketChannel =serverSocketChannel.accept();
//如果是在阻塞的模式下面,这里返回的socketChannel一定不为空,如果是 //在非阻塞的模式下,这里返回的socketChannel可能为空
if(socketChannel != null){
//do something with socketChannel...
}
}