2019独角兽企业重金招聘Python工程师标准>>>

主要思路:

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

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

服务器端代码

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 代替原来的 ChannelFactoryEventLoopGroup bossGroup = new NioEventLoopGroup();EventLoopGroup workerGroup = new NioEventLoopGroup();try {ServerBootstrap serverBootstrap = new ServerBootstrap();serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {@Overridepublic 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();}}
}
package netty.time.server;import io.netty.buffer.ByteBuf;
import io.netty.channel.*;public class TimeServerHandler extends ChannelInboundHandlerAdapter {//ChannelHandlerContext通道处理上下文@Overridepublic 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);}}@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {cause.printStackTrace();ctx.close();}
}

客户端代码

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>() {@Overridepublic 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();}}
}
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 {@Overridepublic 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();}}@Overridepublic 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

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

========END========

转载于:https://my.oschina.net/xinxingegeya/blog/282885

Netty服务器无限循环给客户端发送数据相关推荐

  1. client netty 主动发数据_Netty服务器无限循环给客户端发送数据

    主要思路: * 服务器每隔两秒发送一次服务器的时间 * 客户端接收服务器端数据,打印出服务器的时间 服务器端代码 package netty.time.server; import io.netty. ...

  2. Android客户端 和 pc服务器 建立socket连接并发送数据

    服务器使用java代码 1.服务端需要创建一个ServerSocket(port) 2.port(端口) 地址范围在0~65535请使用1024以上的端口,尽量偏大使用,否则可能和你主机上的其他应用程 ...

  3. C# SuperSocket 手把手教你入门 傻瓜教程---1(服务器单向接收客户端发送数据)

    C# SuperSocket 手把手教你入门 傻瓜教程系列教程 C# SuperSocket 手把手教你入门 傻瓜教程---1(服务器单向接收客户端发送数据) C# SuperSocket 手把手教你 ...

  4. java tcp发消息给硬件_服务器可以使用TCP向客户端发送消息吗?

    如果您有自定义客户端(例如,不是浏览器中的Web应用程序),则可以根据需要与服务器 Build 纯TCP连接 . 但是,TCP上的每次传输都需要双方正在使用的某种数据格式(通常称为"协议&q ...

  5. php 连接socket服务器_PHP-Socket服务端客户端发送接收通信实例详解

    Socket介绍 什么是socket 所谓socket通常也称作"套接字",用于描述IP地址和端口,是一个通信链的句柄.应用程序通常通过"套接字"向网络发出请求 ...

  6. 服务器怎么向指定客户端发送信息,WebSocket 如何实现服务端向客户端发送消息?...

    我们都知道, Websocket 是一个双向的通讯方式,一般情况下,我们都是根据 Client 的情况返回信息,但是在一个更加健壮的系统,我们可能需要主动的向客户端发送消息.我试图在中文网络去搜索,查 ...

  7. Centos 6.5 服务器下面配置邮件客户端 发送报警邮件

    以Centos 系统为例,确保服务器可以正常连接外网 Centos 6.5 下面默认 安装 postfix 查看 rpm -qa | grep postfix postfix-2.6.6-2.2.el ...

  8. python 服务端主动发数据_python使用socket向客户端发送数据的方法

    Python Socket通讯例子详解 创新从模仿开始! python中内置的socket模块使得网络编程更加简单化,下面就通过两个小小脚本来了解客户端如何与服务器端建立socket. 客户端代码: ...

  9. netty发送数据_【Netty】JAVA IO模型

    为什么要学Netty? 其实我们每学一样东西,就要了解学这个的必要性.那么为什么要学Netty呢. 其实但凡涉及网络通信就必然离不开网络编程.Netty目前作为JAVA网络编程最热门的框架,毫不夸张的 ...

最新文章

  1. 删除SQL数据库中事务日志方法
  2. 别骂了,拼多多不挣钱(Doge)
  3. 【数理逻辑】谓词逻辑 ( 谓词逻辑基本等值式 | 消除量词等值式 | 量词否定等值式 | 量词辖域收缩扩张等值式 | 量词分配等值式 )
  4. Java SPI 源码解析及 demo 讲解
  5. 自动平衡男女比例的随机分组软件B2G使用教程,献给组织
  6. 安徽阜阳计算机高中学校排名,安徽阜阳排名靠前的三大高中,有争议?2020年高考成绩说话!...
  7. java中boolean类型占几个字节
  8. 20-mysql-事务
  9. 经营管理类游戏_如何保持精英管理
  10. python用一行代码编写一个回声程序_Python源码分析2 - 一个简单的Python程序的执行...
  11. 互联网舆情监测与分析系统作用及使用功能详解
  12. EverEdit - 值得关注的国产原创开发的免费高效优秀的文本与代码编辑器
  13. 名词用作动词举例_中学文言文词类活用详解:名词活用作动词(一)
  14. mysql出现LF怎么办,MySQL的LF_HASH
  15. zigbee判断首次入网
  16. l003 Driller Augmenting Fuzzing Through Selective Symbolic Execution_2016_NDSS学习笔记
  17. 2011年9月30日
  18. 2021-07-09 终值定理和稳态误差【自动控制原理】
  19. Oracle 设置密码复杂度
  20. [转]Anders Hejlsberg谈C#、Java和C++中的泛型

热门文章

  1. 下一代Jquery模板-----JsRender
  2. JAVA的对象访问定位
  3. Spark:windows下配置spark开发环境
  4. TemplateSyntaxError: 'crispy_forms_tags' is not a registered tag library.报错的解决办法
  5. 转-Android仿微信气泡聊天界面设计
  6. EF 更新条目时出错。有关详细信息,请参见内部异常。
  7. ASP 中调用函数关于Call使用注意的问题
  8. 初级开发人员的7种领导技能:如何为高级职位做准备
  9. mysql limit锁_mysql中limit的用法
  10. php secket5,《Thinkphp5使用Socket服务》 入门篇