服务端:
package com.demo.study1.socket.netty;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
public class EchoServer {
public static void main(String[] args) throws Exception {
Integer PORT = 8080;
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 100)
.handler(new LoggingHandler(LogLevel.DEBUG))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast(new EchoServerHandler());
}
});
// Start the server.
ChannelFuture f = b.bind(PORT).sync();
// Wait until the server socket is closed.
//阻塞主线程,直到网络服务被关闭
f.channel().closeFuture().sync();
} finally {
// Shut down all event loops to terminate all threads.
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
客户端:
package com.demo.study1.socket.netty;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Scanner;
public class NioClient {
public static void main(String[] args) throws IOException {
SocketChannel socketChannel = SocketChannel.open();
socketChannel.configureBlocking(false);
socketChannel.connect(new InetSocketAddress("127.0.0.1", 8080));
while (!socketChannel.finishConnect()) {
Thread.yield();//没连上一直等待
}
Scanner scanner = new Scanner(System.in);
System.out.println("请输入内容:");
String s = scanner.nextLine();
ByteBuffer wrap = ByteBuffer.wrap(s.getBytes());
while (wrap.hasRemaining()) {
socketChannel.write(wrap);
}
System.out.println("等待服务器响应");
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
while (socketChannel.isOpen() && socketChannel.read(byteBuffer) != -1) {
int size = socketChannel.read(byteBuffer);
if (size > 0) {
String msg = new String(byteBuffer.array());
System.out.println(msg.trim());
}
Thread.yield();//等待
}
}
}
将断点打在NioEventLoop的read事件上
先启动服务端,然后启动客户端,首先服务端收到accept事件,放行,客户端输入数据,发送到服务端。
进入read方法
查看pipeline只有三个处理器,头尾和我们自定义的处理器。
开始传播read事件
这个时候是头,他什么都不做,就是把read事件传播给下一个处理器
找下一个处理器,就是我们自定义的处理器
到这里已经将收到的数据,传到我们自定义的处理器。