netty是jboss公司开发的,基于异步的、事件驱动的网络应用程序框架,快速开发高性能、高可靠性的服务器和客户端程序

public class TimeServer {
private int port=;
public void run() throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap(); // (2)
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class) // (3)
.childHandler(new ChannelInitializer<SocketChannel>() { // (4)
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new LineBasedFrameDecoder());
ch.pipeline().addLast(new StringDecoder());
ch.pipeline().addLast(new TimeServerHandler());
}
});
ChannelFuture f = b.bind(port).sync(); // (5)
System.out.println("TimeServer Started on 8080...");
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
new TimeServer().run();
}
}
public class TimeServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { //
String request = (String) msg; //
String response = null;
if ("QUERY TIME ORDER".equals(request)) { //
response = new Date(System.currentTimeMillis()).toString();
} else {
response = "BAD REQUEST";
}
response = response + System.getProperty("line.separator"); //
ByteBuf resp = Unpooled.copiedBuffer(response.getBytes()); //
ctx.writeAndFlush(resp); //
}
}
public class TimeClient {
public static void main(String[] args) throws Exception {
String host = "localhost";
int port = ;
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap(); // (1)
b.group(workerGroup); // (2)
b.channel(NioSocketChannel.class); // (3)
b.handler(new ChannelInitializer<SocketChannel>() {// (4)
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new LineBasedFrameDecoder());
ch.pipeline().addLast(new StringDecoder());
ch.pipeline().addLast(new TimeClientHandler());
}
});
// Start the client.
ChannelFuture f = b.connect(host, port).sync(); // (5)
// Wait until the connection is closed.
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
}
}
}
public class TimeClientHandler extends ChannelInboundHandlerAdapter {
private byte[] req = ("QUERY TIME ORDER" + System.getProperty("line.separator")).getBytes(); @Override
public void channelActive(ChannelHandlerContext ctx) throws InterruptedException {//
sendMsg(ctx);
} public void sendMsg(ChannelHandlerContext ctx) {
Executors.newSingleThreadExecutor().submit(new MsgRunnable(ctx));
} class MsgRunnable implements Runnable {
ChannelHandlerContext ctx; MsgRunnable(ChannelHandlerContext ctx) {
this.ctx = ctx;
} @Override
public void run() {
while (true) {
ByteBuf message = Unpooled.buffer(req.length);
message.writeBytes(req);
ctx.writeAndFlush(message);
try {
Thread.sleep();
} catch (InterruptedException e) {
e.printStackTrace();
} } }
} @Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
String body = (String) msg;
System.out.println("Now is:" + body);
}
}

netty例子-客户端每隔5秒发送查询时间的请求,服务器端响应请求的更多相关文章

  1. 我写的websocket推送例子,每隔5秒服务器向客户端浏览器发送消息(node.js和浏览器)

    node.js服务端 先要安装ws模块的支持 npm install ws 服务端(server.js) var gws; var WebSocketServer = require('ws').Se ...

  2. 关于selenium中的sendKeys()隔几秒发送一个字符

    看一下你的IEDriverServer.exe是不是64位的,我也遇到了这样的问题,换成32位的IEDriverServer.exe,瞬间速度快了

  3. 3、netty第二个例子,使用netty建立客户端,与服务端通讯

    第一个例子中,建立了http的服务器端,可以直接使用curl命令,或者浏览器直接访问. 在第二个例子中,建立一个netty的客户端来主动发送请求,模拟浏览器发送请求. 这里先启动服务端,再启动客户端, ...

  4. 上,打开SSH服务的配置文件:/etc/ssh/sshd_config 加上如下两行: ClientAliveInterval 120 ClientAliveCountMax 720 第一行,表示每隔120秒向客户端

    SSH的默认过一段时间会超时,有时候正在执行着脚本,出去一会回来就断开了,输出信息都看不到了... 禁止SSH自动超时最简单的办法就是,每隔一段时间在客户端和服务器之间发送一个"空包&quo ...

  5. Netty实现客户端和服务端通信简单例子

    Netty是建立在NIO基础之上,Netty在NIO之上又提供了更高层次的抽象. 在Netty里面,Accept连接可以使用单独的线程池去处理,读写操作又是另外的线程池来处理. Accept连接和读写 ...

  6. Unary模式下客户端从开始连接到发送接收数据的主要流程

    (原创)C/C/1.25.0-dev grpc-c/8.0.0, 使用的例子是自带的例子GreeterClient grpc Unary模式下客户端从开始连接到发送数据的主要流程 graph TD; ...

  7. android应用内存占用测试(每隔一秒打印procrank的信息)

    1.内存占用 对于智能手机而言,内存大小是固定的:因此,如果单个app的内存占用越小,手机上可以安装运行的app就越多:或者说app的内存占用越小,在手机上运行就会越流畅.所以说,内存占用的大小,也是 ...

  8. 每隔一秒自动执行函数(JavaScript)

    http://www.cnblogs.com/xlx0210/archive/2010/03/19/1689497.html 1. setInterval() ——每隔一秒自动执行方法,setInte ...

  9. 使用C#解决部分Win8.1系统窗口每隔几秒失去焦点的问题【转】

    使用了Win8.1 With Update 1后,发现重启系统后,当前激活的窗口总是每隔几秒失去焦点,过0.5~1秒焦点回来,导致输入无法正常工作,严重影响使用心情和效率. 在网上找了很久,也没找到相 ...

随机推荐

  1. 学习:多字节编码(ANSI)和UNICODE编码的关系

    Windows 既可以使用 Unicode 字符集又可以使用传统的字符集(如多字节编码)来实现对多种语言的支持,以适应国际市场的要求.与传统的字符集编码相比,Unicode 是世界通用的字符编码标准, ...

  2. CVE-2017-7494复现 Samba远程代码执行

    Samba是在Linux和Unix系统上实现Smb协议的一个免费软件,由服务器及客户端程序构成,Samba服务对应的TCP端口有139.445等.Smb一般作为文件共享服务器,专门提供Linux与Wi ...

  3. 错误解决Caused by: org.hibernate.MappingException: Repeated column in mapping for entity: pers.zhb.domain.Student column: classno (should be mapped with insert="false" update="false")

    1.在学习hibernate的一对多多对一关系的时候,出现了一下错误: 2.错误原因: 这是因为在配置student.hbm.xml的配置文件的时候出现了将两个属性映射到同一个字段: <?xml ...

  4. 使用viper 进行golang 应用的配置管理

    viper 是一个强大的golang 配置管理包,支持多种配置格式内容的读取,同时支持读取key/value 存储的数据 而且不只是读取内容 ,同时也包含了,配置的写入操作. 以下是一个简单的demo ...

  5. python crawler

    crawl blog website: www.apress.com # -*- coding: utf-8 -*- """ Created on Wed May 10 ...

  6. lastal

    http://last.cbrc.jp/doc/lastal.html This program finds local alignments between query sequences, and ...

  7. An internal error occurred during: "Synchronizing"

    An internal error occurred during: "Synchronizing" “同步”期间发生内部错误. 处理方法 :单个文件进行更新,将无法更新的文件进行 ...

  8. [Beta阶段]第二次Scrum Meeting

    Scrum Meeting博客目录 [Beta阶段]第二次Scrum Meeting 基本信息 名称 时间 地点 时长 第二次Scrum Meeting 19/05/03 大运村寝室6楼 40min ...

  9. Mongodb聚合 时间分组(转载)

    // Requires official MongoShell 3.6+ use MediaNetDB; db.getCollection("TestCollection").ag ...

  10. Maven 项目中依赖的搜索顺序

    Maven 项目中依赖的搜索顺序 http://www.manongjc.com/article/13422.html 执行过程中使用 -e -X 查看详细的搜索地址: 1,中央仓库,这是默认的仓库 ...