feat(新增): 🚀 netty的EventLoopIo的客户端和服务端
This commit is contained in:
parent
d2fa8a8cf9
commit
604c958f7d
|
@ -0,0 +1,32 @@
|
||||||
|
package cn.bunny.service.netty.demo2;
|
||||||
|
|
||||||
|
import io.netty.bootstrap.Bootstrap;
|
||||||
|
import io.netty.channel.Channel;
|
||||||
|
import io.netty.channel.ChannelInitializer;
|
||||||
|
import io.netty.channel.nio.NioEventLoopGroup;
|
||||||
|
import io.netty.channel.socket.nio.NioSocketChannel;
|
||||||
|
import io.netty.handler.codec.string.StringEncoder;
|
||||||
|
|
||||||
|
import java.net.InetSocketAddress;
|
||||||
|
|
||||||
|
public class EventLoopIoClient {
|
||||||
|
public static void main(String[] args) throws InterruptedException {
|
||||||
|
Channel channel = new Bootstrap()
|
||||||
|
.group(new NioEventLoopGroup())
|
||||||
|
.channel(NioSocketChannel.class)
|
||||||
|
.handler(new ChannelInitializer<NioSocketChannel>() {
|
||||||
|
@Override
|
||||||
|
protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
|
||||||
|
nioSocketChannel.pipeline().addLast(new StringEncoder());
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.connect(new InetSocketAddress("localhost", 8080))
|
||||||
|
.sync()
|
||||||
|
.channel();
|
||||||
|
|
||||||
|
|
||||||
|
System.out.println(channel);
|
||||||
|
channel.writeAndFlush("你好啊啊啊");
|
||||||
|
System.out.println();
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,36 @@
|
||||||
|
package cn.bunny.service.netty.demo2;
|
||||||
|
|
||||||
|
import io.netty.bootstrap.ServerBootstrap;
|
||||||
|
import io.netty.buffer.ByteBuf;
|
||||||
|
import io.netty.channel.ChannelHandlerContext;
|
||||||
|
import io.netty.channel.ChannelInboundHandlerAdapter;
|
||||||
|
import io.netty.channel.ChannelInitializer;
|
||||||
|
import io.netty.channel.nio.NioEventLoopGroup;
|
||||||
|
import io.netty.channel.socket.nio.NioServerSocketChannel;
|
||||||
|
import io.netty.channel.socket.nio.NioSocketChannel;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
|
import java.nio.charset.Charset;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
public class EventLoopIoServer {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
new ServerBootstrap()
|
||||||
|
.group(new NioEventLoopGroup())
|
||||||
|
.channel(NioServerSocketChannel.class)
|
||||||
|
|
||||||
|
.childHandler(new ChannelInitializer<NioSocketChannel>() {
|
||||||
|
@Override
|
||||||
|
protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
|
||||||
|
nioSocketChannel.pipeline().addLast(new ChannelInboundHandlerAdapter() {
|
||||||
|
@Override
|
||||||
|
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
|
||||||
|
ByteBuf buf = (ByteBuf) msg;
|
||||||
|
log.debug(buf.toString(Charset.defaultCharset()));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.bind(8080);
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue