62,614
社区成员
发帖
与我相关
我的任务
分享
public class TcpClient {
public static void main(String[] args) throws IOException {
//开启网络channel
SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1",88));
socketChannel.write(ByteBuffer.wrap("hello world".getBytes()));
while (true);
}
}
public class ReactorServer {
//开始监听服务
public static void start(Integer port){
try {
//1.服务端开启一个监听通道
ServerSocketChannel serverSocketChannel= ServerSocketChannel.open();
//2.绑定端口
serverSocketChannel.bind(new InetSocketAddress(port));
//3.设置为非阻塞
serverSocketChannel.configureBlocking(false);
//开启一个selector
Selector selector =Selector.open();
//注册channel 和要监听的时间
serverSocketChannel.register(selector,SelectionKey.OP_ACCEPT,new Acceptor(selector,serverSocketChannel));
while (selector.select()>0){
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = selectionKeys.iterator();
//处理事件
while (iterator.hasNext()){
SelectionKey key = iterator.next();
Runnable handler =(Runnable) key.attachment();
handler.run();
//将事件移除
iterator.remove();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
start(88);
}
}
public class Acceptor implements Runnable {
private Selector selector;
private ServerSocketChannel serverSocketChannel;
public Acceptor(Selector selector,ServerSocketChannel serverSocketChannel){
this.selector=selector;
this.serverSocketChannel=serverSocketChannel;
}
@Override
public void run() {
try{
SocketChannel socketChannel = serverSocketChannel.accept();
//设置非阻塞
socketChannel.configureBlocking(false);
//注册selector,并交个dispatchhandler处理
System.out.println("有客户端连接进来");
socketChannel.register(selector,SelectionKey.OP_READ,new DispatchHandler(socketChannel));
}catch (IOException e){
e.printStackTrace();
}
}
}
public class DispatchHandler implements Runnable {
private static Executor executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()<<1);
private SocketChannel socketChannel;
public DispatchHandler(SocketChannel socketChannel){
this.socketChannel= socketChannel;
}
@Override
public void run() {
System.out.println("开启线程处理读写事件");
//通过线程池
executor.execute(new ReadHandler(socketChannel));
}
}
public class ReadHandler implements Runnable {
private SocketChannel socketChannel;
public ReadHandler(SocketChannel socketChannel){
this.socketChannel=socketChannel;
}
@Override
public void run() {
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
Charset charset = Charset.forName("utf-8");
try {
while (socketChannel.read(byteBuffer)>0){
byteBuffer.flip();
System.out.println(charset.decode(byteBuffer).toString());
}
byteBuffer.clear();
//数据回写
socketChannel.write(ByteBuffer.wrap("收到".getBytes()));
}catch (IOException e){
e.printStackTrace();
}
}
}