TimeServer.java

package netty.timeserver.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; public class TimeServer { public void bind(int port) throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
// 配置服务器的NIO线程租
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 1024)
.childHandler(new ChildChannelHandler()); // 绑定端口,同步等待成功
ChannelFuture f = b.bind(port).sync();
// 等待服务端监听端口关闭
f.channel().closeFuture().sync();
} finally {
// 优雅退出,释放线程池资源
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
} private class ChildChannelHandler extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel arg0) throws Exception {
System.out.println("server initChannel..");
arg0.pipeline().addLast(new TimeServerHandler());
}
} public static void main(String[] args) throws Exception {
int port = 9000;
if (args != null && args.length > 0) {
try {
port = Integer.valueOf(args[0]);
} catch (NumberFormatException e) { }
} new TimeServer().bind(port);
}
}

TimeServerHandler.java

package netty.timeserver.server;

import java.util.Date;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter; public class TimeServerHandler extends ChannelInboundHandlerAdapter { @Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
throws Exception {
System.out.println("server channelRead..");
ByteBuf buf = (ByteBuf) msg;
byte[] req = new byte[buf.readableBytes()];
buf.readBytes(req);
String body = new String(req, "UTF-8");
System.out.println("The time server receive order:" + body);
String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new Date(
System.currentTimeMillis()).toString() : "BAD ORDER";
ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
ctx.write(resp);
} @Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
System.out.println("server channelReadComplete..");
ctx.flush();//刷新后才将数据发出到SocketChannel
} @Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
System.out.println("server exceptionCaught..");
ctx.close();
} }

TimeClient.java

package netty.timeserver.client;

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 void connect(int port, String host) throws Exception {
// 配置客户端NIO线程组
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel arg0)
throws Exception {
System.out.println("client initChannel..");
arg0.pipeline().addLast(new TimeClientHandler());
}
});
// 发起异步连接操作
ChannelFuture f = b.connect(host, port).sync();
// 等待客户端链路关闭
f.channel().closeFuture().sync();
} finally {
// 优雅退出,释放NIO线程组
group.shutdownGracefully();
}
} public static void main(String[] args) throws Exception {
int port = 9000;
if (args != null && args.length > 0) {
try {
port = Integer.parseInt(args[0]);
} catch (Exception e) {
}
}
new TimeClient().connect(port, "127.0.0.1");
}
}

TimeClientHandler.java

package netty.timeserver.client;

import java.util.logging.Logger;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter; public class TimeClientHandler extends ChannelInboundHandlerAdapter { private static final Logger logger = Logger
.getLogger(TimeClientHandler.class.getName()); private final ByteBuf firstMessage; public TimeClientHandler() {
byte[] req = "QUERY TIME ORDER".getBytes();
firstMessage = Unpooled.buffer(req.length);
firstMessage.writeBytes(req);
} @Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
//与服务端建立连接后
System.out.println("client channelActive..");
ctx.writeAndFlush(firstMessage);
} @Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
throws Exception {
System.out.println("client channelRead..");
//服务端返回消息后
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 exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
System.out.println("client exceptionCaught..");
// 释放资源
logger.warning("Unexpected exception from downstream:"
+ cause.getMessage());
ctx.close();
} }

netty入门实例的更多相关文章

  1. Netty入门实例及分析

    什么是netty?以下是官方文档的简单介绍: The Netty project  is an effort to provide an asynchronous event-driven netwo ...

  2. netty入门(一)

    1. netty入门(一) 1.1. 传统socket编程 在任何时候都可能有大量的线程处于休眠状态,只是等待输入或者输出数据就绪,这可能算是一种资源浪费. 需要为每个线程的调用栈都分配内存,其默认值 ...

  3. Netty入门(一)之webSocket聊天室

    一:简介 Netty 是一个提供 asynchronous event-driven (异步事件驱动)的网络应用框架,是一个用以快速开发高性能.高可靠性协议的服务器和客户端. 换句话说,Netty 是 ...

  4. Netty入门二:开发第一个Netty应用程序

    Netty入门二:开发第一个Netty应用程序 时间 2014-05-07 18:25:43  CSDN博客 原文  http://blog.csdn.net/suifeng3051/article/ ...

  5. Java网络编程 -- Netty入门

    Netty简介 Netty是一个高性能,高可扩展性的异步事件驱动的网络应用程序框架,它极大的简化了TCP和UDP客户端和服务器端网络开发.它是一个NIO框架,对Java NIO进行了良好的封装.作为一 ...

  6. Netty入门与实战教程总结分享

    前言:都说Netty是Java程序员必须要掌握的一项技能,带着不止要知其然还要知其所以然的目的,在慕课上找了一个学习Netty源码的教程,看了几章后着实有点懵逼.虽然用过Netty,并且在自己的个人网 ...

  7. Java IO学习笔记八:Netty入门

    作者:Grey 原文地址:Java IO学习笔记八:Netty入门 多路复用多线程方式还是有点麻烦,Netty帮我们做了封装,大大简化了编码的复杂度,接下来熟悉一下netty的基本使用. Netty+ ...

  8. Netty入门(三):EventLoop

    前言 Netty系列索引: 1.Netty入门(一):ByteBuf 2.Netty入门(二):Channel IO相关: 1.Java基础(一):I/O多路复用模型及Linux中的应用 上文提到,早 ...

  9. Netty入门(二):Channel

    前言 Netty系列索引: 1.Netty入门(一):ByteBuf 2.Netty入门(二):Channel 在Netty框架中,Channel是其中之一的核心概念,是Netty网络通信的主体,由它 ...

随机推荐

  1. rac 11g_生产库日志组损坏处理

    原创作品,出自 "深蓝的blog" 博客,转载时请务必注明出处,否则有权追究版权法律责任. 深蓝的blog:http://blog.csdn.net/huangyanlong/ar ...

  2. $.ajax提交,后台接受到的值总是乱码?明天再总结

    //首先说明,我的服务器和页面编码都是GBK,所以尝试了很多种GBK的方式前台:function printFunction(){ window.print(); $.ajax({ url : '/t ...

  3. Phython 学习笔记之——类的初步认识

    类是面向对象编程的核心,他扮演相关数据及逻辑容器的角色.他们提供了创建实例对象的蓝图.因为python语言不要求必须以面向对象的方式编程(与JAVA不同),这里简单的举一个例子. 如何定义一个类 cl ...

  4. c# 获取 webbrowser 完整 cookie

    下面的代码实现的功能确实如标题所言,但要求是获取的是当前进程内的webbrowser,跨进程或引用的ShellWindows对象无效, 哎我本来两种情况都要用,只把前者代码先记下: internal ...

  5. urllib2

    import urllib2response = urllib2.urlopen("http://www.baidu.com")print response.read() urlo ...

  6. Web前端开发笔试&面试_03

    WL: 1.如何显示.隐藏一个dom对象? 2.如何将一个网页中的内容水平置中?写出重要的html标签和css. (css:#content{align:center;float:left;}html ...

  7. unity, sceneview 中拾取球体gizmos

    http://answers.unity3d.com/questions/745560/handle-for-clickable-scene-objects.html http://www.jians ...

  8. OpenJudge计算概论-求平均年龄

    /*============================================== 求平均年龄 总时间限制: 1000ms 内存限制: 65536kB 描述 班上有学生若干名,给出每名学 ...

  9. Jfinal基础学习(一)

    我负责的项目都是Jfinal的了,有必要写一些学习知识,记录下来. 1.PropKit.use("config.txt", "UTF-8"); PropKit ...

  10. oracle11gRAC环境使用RMAN增量备份方案

    转摘:http://blog.itpub.net/29819001/viewspace-1320977/ [oracle@zx ~]$ rman target /Recovery Manager: R ...