Netty的socket编程(四)
2021-07-03 18:05
标签:put bootstrap net handle active final tin rup write Netty提供的handler:编解码,消息头,消息编码 1. 连接建立后,客户端和服务端都不会主动发消息,实现handler的channelActive来触发消息发送。 2.SimpleChannelInboundHandler的重载方法 (1)handlerAdded 连接建立时调用 (2)HandlerRemoved 连接断开时调用 (3)HandlerActive 连接处于活动状态调用 (4)HandlerInactive 连接处于不活动状态调用 socket示例 : server启动类: server初始化类 : server业务处理handler: client 类: client启动类: client初始化类 : client业务处理handler : Netty的socket编程(四) 标签:put bootstrap net handle active final tin rup write 原文地址:http://www.cnblogs.com/fubinhnust/p/7123577.html 1 public class MyServer {
2
3 public static void main(String[] args) throws InterruptedException {
4
5 EventLoopGroup bossGroup = new NioEventLoopGroup();
6 EventLoopGroup workerGroup = new NioEventLoopGroup();
7
8 try{
9 ServerBootstrap serverBootstrap = new ServerBootstrap();
10 serverBootstrap.group(bossGroup,workerGroup).
11 channel(NioServerSocketChannel.class)
12 .childHandler(new MyServerInitializer());
13 ChannelFuture channelFuture = serverBootstrap.bind(8899).sync();
14 channelFuture.channel().closeFuture().sync();
15
16 }finally {
17
18 bossGroup.shutdownGracefully();
19 workerGroup.shutdownGracefully();
20
21 }
22
23 }
24
25 }
1 public class MyServerInitializer extends ChannelInitializer
1 public class MyServerHandler extends SimpleChannelInboundHandler
1 public class MyClient {
2
3 public static void main(String[] args) throws InterruptedException {
4
5 EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
6
7 try{
8 Bootstrap bootstrap = new Bootstrap();
9 bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class)
10 .handler(new MyClientInitializer());
11
12 ChannelFuture channelFuture = bootstrap.connect("localhost",8899).sync();
13 channelFuture.channel().closeFuture().sync();
14 }finally {
15 eventLoopGroup.shutdownGracefully();
16 }
17
18
19 }
20
21 }
1 public class MyClientInitializer extends ChannelInitializer
1 public class MyClientHandler extends SimpleChannelInboundHandler
文章标题:Netty的socket编程(四)
文章链接:http://soscw.com/index.php/essay/101373.html