netty 例子
2016-03-21 18:54
441 查看
客户端:
public class TimeClient {
public void connect(int port, String host){
EventLoopGroup group = new NioEventLoopGroup();
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.handler(new ChildChannelHandler());
try {
ChannelFuture f = b.connect(host, port).sync();
f.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}
finally{
group.shutdownGracefully();
}
}
class ChildChannelHandler extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new TimeClientHandler());
}
}
class TimeClientHandler extends ChannelHandlerAdapter {
private final Logger logger =
Logger.getLogger(TimeClientHandler
.class.getSimpleName());
private ByteBuf firstMessage;
public TimeClientHandler(){
byte[] req = "query".getBytes();
firstMessage = Unpooled.buffer(req.length);
firstMessage.writeBytes(req);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
throws Exception {
ByteBuf buf = (ByteBuf)msg;
byte[] req = new byte[buf.readableBytes()];
buf.readBytes(req);
String body = new String(req , "UTF-8");
System.out.println("now is : " + body);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
logger.info("Unexpected exception from downstream : "
+ cause.getMessage());
ctx.close();
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
super.channelActive(ctx);
ctx.writeAndFlush(firstMessage);
}
}
public static void main(String[] args) {
new TimeClient().connect(6666, "127.0.0.1");
}
}
服务端:
public class TimeServer {
public void bind(int port) {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 1024)
.childHandler(new ChildChannelHandler());
ChannelFuture f = serverBootstrap.bind(port).sync();
f.channel().closeFuture().sync();
} catch (Exception ex) {
System.err.println(ex.getLocalizedMessage());
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
class ChildChannelHandler extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new TimeServerHandler());
}
}
class TimeServerHandler extends ChannelHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf buf = (ByteBuf)msg;
byte[] req = new byte[buf.readableBytes()];
buf.readBytes(req);
String body = new String(req , "UTF-8");
System.out.println("server receive : " + body);
String currentTime = "query".equalsIgnoreCase(body)
? new java.util.Date(System.currentTimeMillis()).toString()
: "bad order";
ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
ctx.write(resp);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
}
}
public static void main(String[] args) {
new TimeServer().bind(6666);
}
}
public class TimeClient {
public void connect(int port, String host){
EventLoopGroup group = new NioEventLoopGroup();
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.handler(new ChildChannelHandler());
try {
ChannelFuture f = b.connect(host, port).sync();
f.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}
finally{
group.shutdownGracefully();
}
}
class ChildChannelHandler extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new TimeClientHandler());
}
}
class TimeClientHandler extends ChannelHandlerAdapter {
private final Logger logger =
Logger.getLogger(TimeClientHandler
.class.getSimpleName());
private ByteBuf firstMessage;
public TimeClientHandler(){
byte[] req = "query".getBytes();
firstMessage = Unpooled.buffer(req.length);
firstMessage.writeBytes(req);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
throws Exception {
ByteBuf buf = (ByteBuf)msg;
byte[] req = new byte[buf.readableBytes()];
buf.readBytes(req);
String body = new String(req , "UTF-8");
System.out.println("now is : " + body);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
logger.info("Unexpected exception from downstream : "
+ cause.getMessage());
ctx.close();
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
super.channelActive(ctx);
ctx.writeAndFlush(firstMessage);
}
}
public static void main(String[] args) {
new TimeClient().connect(6666, "127.0.0.1");
}
}
服务端:
public class TimeServer {
public void bind(int port) {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 1024)
.childHandler(new ChildChannelHandler());
ChannelFuture f = serverBootstrap.bind(port).sync();
f.channel().closeFuture().sync();
} catch (Exception ex) {
System.err.println(ex.getLocalizedMessage());
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
class ChildChannelHandler extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new TimeServerHandler());
}
}
class TimeServerHandler extends ChannelHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf buf = (ByteBuf)msg;
byte[] req = new byte[buf.readableBytes()];
buf.readBytes(req);
String body = new String(req , "UTF-8");
System.out.println("server receive : " + body);
String currentTime = "query".equalsIgnoreCase(body)
? new java.util.Date(System.currentTimeMillis()).toString()
: "bad order";
ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
ctx.write(resp);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
}
}
public static void main(String[] args) {
new TimeServer().bind(6666);
}
}
相关文章推荐
- redis集群部署
- python的with语句理解
- myeclipse 自定义xml模板,供新建xml文件时自动导入 (转)
- 在WAMPSERVER下增加多版本的PHP(PHP5.3,PHP5.4,PHP5.5)支持。
- Jfinal Generator 不需要生成带某个前缀的表名数组的方法
- 57.解决版本控制中 UserInterfaceState.xcuserstate 文件频繁变动
- 新安装的金蝶K3软件,初始化后,在基础资料中对于币别,科目,部门,客户等资料均无法新增,无法引出,等操作,K3CASysSet.dll
- Spring3第二天
- thrift的TTransport连接池注意事项[Java版本说明]
- Mastering R plot -2
- 内网渗透一:利用Xss漏洞进入内网
- Spring MVC返回对象JSON
- 统计输入字符串中各字符出现的次数
- Android一个应用(APK)多个入口的实现方式整理
- 安卓--selector简单使用
- autorelease 应用
- 后台进行数据更新和下载
- PHP/JS/MYSQL 测试题
- 简单AIDS的源码学习 <utils.c>
- Java泛型简明教程