一、我的开发环境
- eclipse-jee-indigo-SR2-win32-x86_64
- JDK1.7
- windows-64
- netty-all-4.1.1.Final-sources 下载地址:http://netty.io/ ,从【Downloads】选择下载netty-all-4.1.1.Final-sources。
- 创建一个java工程,选中项目右键Properties->Java Build Path->Add External JARS->将netty-all-4.1.1.Final.jar包导入到项目中
二 、Netty服务器端开发
2.1代码示例
创建服务启动类HttpServer,既然作为服务器它肯定和tomcat服务器一样有个开关来开启/关闭服务器,可以在类中看到有个main函数。对的,它的启动方式就是右键->Run As->Java Application
- package com.lll.game;
-
- import org.apache.commons.logging.Log;
- import org.apache.commons.logging.LogFactory;
-
- 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 HttpServer {
- private static Log log = LogFactory.getLog(HttpServer.class);
-
- public static void main(String[] args) throws Exception {
- HttpServer server = new HttpServer();
- log.info("服务已启动...");
- server.start(8844);
- }
-
- public void start(int port) throws Exception {
-
- EventLoopGroup bossGroup = new NioEventLoopGroup();
- EventLoopGroup workerGroup = new NioEventLoopGroup();
- try {
- ServerBootstrap b = new ServerBootstrap();
- b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
- .childHandler(new ChannelInitializer<SocketChannel>() {
- @Override
- public void initChannel(SocketChannel ch) throws Exception {
- ch.pipeline().addLast(new ServerHandler());
- }
- }).option(ChannelOption.SO_BACKLOG, 128)
- .childOption(ChannelOption.SO_KEEPALIVE, true);
-
- ChannelFuture f = b.bind(port).sync();
-
- f.channel().closeFuture().sync();
- } finally {
-
- workerGroup.shutdownGracefully();
- bossGroup.shutdownGracefully();
- }
- }
- }
创建ServerHandler类来负责对网络事件进行读写操作
- package com.lll.game;
-
- import io.netty.channel.ChannelHandlerAdapter;
- import io.netty.channel.ChannelHandlerContext;
-
- public class ServerHandler extends ChannelHandlerAdapter{
- @Override
- public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
- super.handlerAdded(ctx);
- System.out.println(ctx.channel().id()+"进来了");
- }
-
- @Override
- public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
- super.handlerRemoved(ctx);
- System.out.println(ctx.channel().id()+"离开了");
- }
-
- }
提示:本书作者使用的是netty是用的5.0,我在官方下载的时候只找到4.x包(据说5.0好像已经被官方废弃了)。2个版本相比较,不同版本ChannelHandler申明的方法不一样!!
2.2 Netty5.x与4.x代码上的差异
在4.x中,ChannelHandlerAdapter里的channelRead方法在ChannelInboundHandlerAdapter抽象类中,同5.X一样ChannelInboundHandlerAdapter也是基于ChannelHandler接口。这样用户可以方便地进行业务逻辑定制,例如:打印日志、统一封装异常信息、性能统计和消息编码解码等。
ChannelInboundHandlerAdapter的UML图如下:
2.3 4.x ServerHandler类
- package com.game.lll.net;
-
- import java.util.Date;
-
标签:
Unity