Netty学习笔记——(一)

因为一些原因最近在做游戏服务器,没有在涉及游戏前端的一些东西。因为现在用的是C++,也看了一段时间delphi的服务端代码。大致的框架理解了一些,但是因为是公司的项目。所以也不便于拿出来总结。自己想用自己比较熟悉的Java,来做一个简单的服务端测试用。也让自己有一个“作品”也或是“筹码”。

Java NIO框架有MINA、Netty这些很现成的框架,自己前一段时间看了一下MINA的测试代码,也自己测试了一下,之所以没有选择MINA,仅仅是MINA的代码看着不够简洁这个不是理由的理由,并且MINA他的日志用的log4J,在引入外部包,源代码学习上存在嵌套部分。为了理解和学习上更加的流畅,Netty更成体系一些,所以选择了Netty来做自己Java服务器的学习入门框架。

参考资料Netty官网提供:http://netty.io/wiki/user-guide-for-4.x.html

Netty介绍:

Netty是一个封装的Java NIO框架,他提供一种方式来处理网络编程例如:TCP或UDP Socket Server开发,并且也提供HTTP,FTP,SMTP。除此之外Netty是一套客户端/服务端框架,因此客户端亦可以使用。据称:Netty的效率要比MINA的高,而MINA自称效率接近C/C++的效率,具体没有自己测试过,所以很难置评。

准备:

下载Netty4.*的开发包(关于4.*的分包规则,可以详见4.*与3.*差异介绍的官方文章)

安装JDK1.7 or above

实例:(以下需要引入的Netty的包名:netty-transport-4.0.13.Final.jar,netty-common-4.0.13.Final.jar,netty-buffer-4.0.13.Final.jar

/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
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 DiscardServer {

    private final int port;

    public DiscardServer(int port) {
        this.port = port;
    }

    public void run() throws Exception {
        //bossGroup,workerGroup都是管理类,创建管理实例,设置实例。Boss和worker之间的关系很好理解
        //Boss,负责连接的管理
        EventLoopGroup bossGroup = new NioEventLoopGroup(); //通过构造函数可以设置处理线程数
        //worker,一旦Boss接受连接,注册连接到worker
        EventLoopGroup workerGroup = new NioEventLoopGroup(); //通过构造函数可以设置处理线程数
        
        try {
            ServerBootstrap b = new ServerBootstrap();//设置Server的类函数,服务器引导程序实例化
            b.group(bossGroup, workerGroup) 
             .channel(NioServerSocketChannel.class)//实例化一个新频道注册连接
             .childHandler(new ChannelInitializer<SocketChannel>() { //初始化添加SocketChannel
                 @Override
                 public void initChannel(SocketChannel ch) throws Exception {
                     ch.pipeline().addLast(new DiscardServerHandler());
                 }
             });

            // Bind and start to accept incoming connections.绑定port
            ChannelFuture f = b.bind(port).sync();

            // Wait until the server socket is closed.
            // In this example, this does not happen, but you can do that to gracefully
            // shut down your server.
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        int port = 8080;
        new DiscardServer(port).run();
    }
}

在上面我们创建Netty 的一个简单的NIO框架,但是SocketChannel注册的Handler并没有实例化,因此我们应当还要创建DiscardServerHandler.java,如下:

import io.netty.buffer.*;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;

/**
 * Handles a server-side channel.
 */
public class DiscardServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        ByteBuf in = (ByteBuf) msg;
        try {
            while (in.isReadable()) { //读操作
//                System.out.print((char) in.readByte()); //打印接受道德信息
//                System.out.flush();
            }
        } finally {
            ReferenceCountUtil.release(msg); //
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { 
        cause.printStackTrace();//抛异常
        ctx.close();
    }
}

转载于:https://www.cnblogs.com/flashbird/p/3476344.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值