netty编写一个简单的聊天程序(六)
2021-07-03 18:07
标签:ring ddl throws text 处理器 nec pipe reader finally 1.编写服务端 server启动类:” server初始化类: server端业务处理handler :增加连接实例集合 ChannelGroup 2.编写客户端 client启动类 : client初始化类 client消息接收处理handler: netty编写一个简单的聊天程序(六) 标签:ring ddl throws text 处理器 nec pipe reader finally 原文地址:http://www.cnblogs.com/fubinhnust/p/7123612.html 1 public class MyChatServer {
2
3 public static void main(String[] args) throws InterruptedException {
4
5
6 EventLoopGroup bossGroup = new NioEventLoopGroup();
7 EventLoopGroup workerGroup = new NioEventLoopGroup();
8
9 try{
10 ServerBootstrap serverBootstrap = new ServerBootstrap();
11 serverBootstrap.group(bossGroup,workerGroup).
12 channel(NioServerSocketChannel.class)
13 .childHandler(new MyChatServerInitializer());
14
15 ChannelFuture channelFuture = serverBootstrap.bind(8899).sync();
16 channelFuture.channel().closeFuture().sync();
17 }finally {
18 bossGroup.shutdownGracefully();
19 workerGroup.shutdownGracefully();
20 }
21
22
23 }
24
25 }
1 public class MyChatServerInitializer extends ChannelInitializer
1 public class MyChatServerHandler extends SimpleChannelInboundHandler
1 public class MyChatClient {
2
3 public static void main(String[] args) throws InterruptedException, IOException {
4
5 EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
6
7 try{
8 Bootstrap bootstrap = new Bootstrap();
9 bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class)
10 .handler(new MyChatClientInitializer());
11
12 Channel channel = bootstrap.connect("localhost",8899).sync().channel();
13
14 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
15 for(;;){
16 channel.writeAndFlush(br.readLine() + "\r\n");
17 }
18
19 }finally {
20 eventLoopGroup.shutdownGracefully();
21 }
22
23 }
24
25 }
1 public class MyChatClientInitializer extends ChannelInitializer
1 public class MyChatClientHandler extends SimpleChannelInboundHandler