服务端
package com.synda.selector;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
public class ServerStart {
public static void main(String[] args) throws Exception{
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.configureBlocking(false);
ssc.bind(new InetSocketAddress(8888));
//获取多路复用选择器
Selector selector = Selector.open();
//绑定监听器,并监听接入事件;
ssc.register(selector,SelectionKey.OP_ACCEPT);
while (true){
//这个方法会产生阻塞,如果没有任何客户端接入,则会阻塞所有线程;
//放开的条件是有接入事件发生;即有客户端接入
selector.select();
//如果代码走到这里,说明阻塞放开,说明有事件发生,即需要处理事件
Set<SelectionKey> set = selector.selectedKeys();
Iterator<SelectionKey> it = set.iterator();
while (it.hasNext()){
//获取一个具体的事件
SelectionKey sk = it.next();
//表示有客户端接入
if (sk.isAcceptable()){
//建立通道
ServerSocketChannel server = (ServerSocketChannel) sk.channel();
//建立和客户端通信的通道;
SocketChannel sc = server.accept();
//改成非阻塞模式
sc.configureBlocking(false);
//注册事件
//注册读和写事件
System.out.println("处理线程号为="+Thread.currentThread().getId());
sc.register(selector,SelectionKey.OP_READ|SelectionKey.OP_WRITE);
}
//表示客户端发过来数据,服务端需要读取数据
if (sk.isReadable()){
SocketChannel sc = (SocketChannel) sk.channel() ;
ByteBuffer buffer = ByteBuffer.allocate(10);
sc.read(buffer);
System.out.println("收到客户端数据:"+new String(buffer.array())+"线程号为:"+Thread.currentThread().getId());
}
//表示客户端已经准备好接受数据,服务端要写出数据
if (sk.isWritable()){
SocketChannel sc =(SocketChannel) sk.channel();
ByteBuffer buffer = ByteBuffer.wrap("1804".getBytes());
while (buffer.hasRemaining()){
sc.write(buffer);
}
}
//事件处理完后,移除此事件,避免重复处理
it.remove();
}
}
}
}
客户端
package com.synda.selector;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
public class ClientStart {
public static void main(String[] args) throws IOException {
SocketChannel sc = SocketChannel.open();
//设置为非阻塞模式
sc.configureBlocking(false);
sc.connect(new InetSocketAddress("127.0.0.1",8888));
//防止sc没有真正连接上,发生空指针异常;
while (!sc.isConnected()){
sc.finishConnect();
}
ByteBuffer buffer = ByteBuffer.wrap("hello word".getBytes());
sc.write(buffer);
ByteBuffer buffer1 = ByteBuffer.allocate(4);
//为了避免读到空数据判断position和limit中是否还有
/**
* 因为write和read是非阻塞方法;
* 所以为了确保读写数据完整,需要加上hasRemaining()
*/
while (buffer1.hasRemaining()){
sc.read(buffer1);
}
System.out.println("客户端收到数据:"+new String(buffer1.array()));
// System.out.println("scuuess,成功接入服务端");
//客户端线程一直开启
while (true);
}
}