转载:Netty服务器无限循环给客户端发送数据

本文介绍使用 Netty 框架实现时间服务器和客户端的通信过程,服务器每两秒发送一次当前时间,客户端接收并打印服务器时间。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转载:版权归原作者所有

主要思路:

* 服务器每隔两秒发送一次服务器的时间

* 客户端接收服务器端数据,打印出服务器的时间

 

服务器端代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package  netty.time.server;
 
import  io.netty.bootstrap.ServerBootstrap;
import  io.netty.channel.ChannelFuture;
import  io.netty.channel.ChannelInitializer;
import  io.netty.channel.ChannelOption;
import  io.netty.channel.EventLoopGroup;
import  io.netty.channel.nio.NioEventLoopGroup;
import  io.netty.channel.socket.SocketChannel;
import  io.netty.channel.socket.nio.NioServerSocketChannel;
import  io.netty.handler.timeout.ReadTimeoutHandler;
import  io.netty.handler.timeout.WriteTimeoutHandler;
 
/**
  * Created with IntelliJ IDEA.
  * User: ASUS
  * Date: 14-5-7
  * Time: 上午10:10
  * To change this template use File | Settings | File Templates.
  */
public  class  TimeServer {
 
     public  static  void  main(String[] args) {
         // EventLoop 代替原来的 ChannelFactory
         EventLoopGroup bossGroup =  new  NioEventLoopGroup();
         EventLoopGroup workerGroup =  new  NioEventLoopGroup();
         try  {
             ServerBootstrap serverBootstrap =  new  ServerBootstrap();
             serverBootstrap.group(bossGroup, workerGroup)
                     .channel(NioServerSocketChannel. class )
                     .childHandler( new  ChannelInitializer<SocketChannel>() {
                         @Override
                         public  void  initChannel(SocketChannel ch)  throws  Exception {
                             ch.pipeline().addLast(
                                     new  TimeServerHandler(),
                                     new  WriteTimeoutHandler( 10 ),
                                     //控制写入超时10秒构造参数10表示如果持续10秒钟都没有数据写了,那么就超时。
                                     new  ReadTimeoutHandler( 10 )
                             );
                         }
                     }).option(ChannelOption.SO_KEEPALIVE,  true );
             ChannelFuture f = serverBootstrap.bind( 9090 ).sync();
             f.channel().closeFuture().sync();
         catch  (InterruptedException e) {
         finally  {
             workerGroup.shutdownGracefully();
             bossGroup.shutdownGracefully();
         }
     }
}
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package  netty.time.server;
 
import  io.netty.buffer.ByteBuf;
import  io.netty.channel.*;
 
 
public  class  TimeServerHandler  extends  ChannelInboundHandlerAdapter {
 
 
     //ChannelHandlerContext通道处理上下文
     @Override
     public  void  channelActive( final  ChannelHandlerContext ctx)  throws  InterruptedException {  // (1)
 
         while  ( true ) {
             ByteBuf time = ctx.alloc().buffer( 4 );  //为ByteBuf分配四个字节
             time.writeInt(( int ) (System.currentTimeMillis() / 1000L + 2208988800L));
             ctx.writeAndFlush(time);  // (3)
             Thread.sleep( 2000 );
         }
     }
 
     @Override
     public  void  exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
         cause.printStackTrace();
         ctx.close();
     }
}

 

客户端代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package  netty.time.server;
 
import  io.netty.bootstrap.Bootstrap;
import  io.netty.channel.ChannelFuture;
import  io.netty.channel.ChannelInitializer;
import  io.netty.channel.ChannelOption;
import  io.netty.channel.EventLoopGroup;
import  io.netty.channel.nio.NioEventLoopGroup;
import  io.netty.channel.socket.SocketChannel;
import  io.netty.channel.socket.nio.NioSocketChannel;
 
 
/**
  * 服务器每隔两秒发送一次服务器的时间
  * 客户端接收服务器端数据,打印出服务器的时间
  */
public  class  TimeClient {
     public  static  void  main(String[] args)  throws  Exception {
         EventLoopGroup workerGroup =  new  NioEventLoopGroup();
 
         try  {
             Bootstrap b =  new  Bootstrap();  // (1)
             b.group(workerGroup);  // (2)
             b.channel(NioSocketChannel. class );  // (3)
             b.option(ChannelOption.SO_KEEPALIVE,  true );  // (4)
             b.handler( new  ChannelInitializer<SocketChannel>() {
                 @Override
                 public  void  initChannel(SocketChannel ch)  throws  Exception {
                     ch.pipeline().addLast( new  TimeClientHandler());
                 }
             });
 
             // Start the client.
             ChannelFuture f = b.connect( "127.0.0.1" 9090 ).sync();  // (5)
 
             // Wait until the connection is closed.
             f.channel().closeFuture().sync();
         finally  {
             workerGroup.shutdownGracefully();
         }
     }
}
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package  netty.time.server;
 
import  io.netty.buffer.ByteBuf;
import  io.netty.channel.ChannelHandlerContext;
import  io.netty.channel.ChannelInboundHandlerAdapter;
 
import  java.util.Date;
 
public  class  TimeClientHandler  extends  ChannelInboundHandlerAdapter {
     @Override
     public  void  channelRead(ChannelHandlerContext ctx, Object msg) {
         ByteBuf m = (ByteBuf) msg;
         try  {
             long  currentTimeMillis = (m.readUnsignedInt() - 2208988800L) * 1000L;
             System.out.println( new  Date(currentTimeMillis));
         finally  {
             m.release();
         }
     }
 
     @Override
     public  void  exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
         cause.printStackTrace();
         ctx.close();
     }
}

 

运行结果:

Sun Jun 22 18:40:42 CST 2014

Sun Jun 22 18:40:44 CST 2014

Sun Jun 22 18:40:46 CST 2014

Sun Jun 22 18:40:48 CST 2014

Sun Jun 22 18:40:50 CST 2014

Sun Jun 22 18:40:52 CST 2014

Sun Jun 22 18:40:54 CST 2014

Sun Jun 22 18:40:56 CST 2014

Sun Jun 22 18:40:58 CST 2014

Sun Jun 22 18:41:00 CST 2014

Sun Jun 22 18:41:02 CST 2014

Sun Jun 22 18:41:04 CST 2014

Sun Jun 22 18:41:06 CST 2014

Sun Jun 22 18:41:08 CST 2014

Sun Jun 22 18:41:10 CST 2014

Sun Jun 22 18:41:12 CST 2014

Sun Jun 22 18:41:14 CST 2014

Sun Jun 22 18:41:16 CST 2014

Sun Jun 22 18:41:18 CST 2014

Sun Jun 22 18:41:20 CST 2014

Sun Jun 22 18:41:22 CST 2014

Sun Jun 22 18:41:24 CST 2014

Sun Jun 22 18:41:26 CST 2014

Sun Jun 22 18:41:28 CST 2014

Sun Jun 22 18:41:30 CST 2014

.................................

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值