ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

java游戏服务器——Netty网络服务

2021-12-10 13:02:15  阅读:174  来源: 互联网

标签:Netty java 网络服务 void private return new Integer public


java游戏服务器架构中,请多多指教——manREDoo

定义消息头

/**
 * <p>
 * 消息头
 * 魔法头short+版本号byte+长度int+协议命令号short+唯一序列号
 * </p>
 *
 * @author : 钟满红
 */
public class MessageHead {
    public static final short MESSAGE_HEADER_FLAG = 0x2425;

    /**
     * 魔法头
     */
    private Short head;
    /**
     * 版本号
     */
    private Integer version;
    /**
     * 长度
     */
    private Integer length;
    /**
     * 命令
     */
    private Integer cmd;
    /**
     * 序列号
     */
    private Integer serial;

    public MessageHead(){
        this.head = MESSAGE_HEADER_FLAG;
    }

    public Short getHead() {
        return head;
    }

    public void setHead(Short head) {
        this.head = head;
    }

    public Integer getVersion() {
        return version;
    }

    public void setVersion(Integer version) {
        this.version = version;
    }

    public Integer getLength() {
        return length;
    }

    public void setLength(Integer length) {
        this.length = length;
    }

    public Integer getCmd() {
        return cmd;
    }

    public void setCmd(Integer cmd) {
        this.cmd = cmd;
    }

    public Integer getSerial() {
        return serial;
    }

    public void setSerial(Integer serial) {
        this.serial = serial;
    }
}

定义消息体

/**
 * <p>
 * 消息内容
 * </p>
 *
 * @author : 钟满红
 */
public class MessageBody {
    /**
     * 存储数据
     */
    private String data;

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }
}

消息包

/**
 * <p>
 * 消息的实现
 * </p>
 *
 * @author : 钟满红
 */
public class NetMessage{
    private MessageHead messageHead;
    private MessageBody messageBody;

    public MessageHead getMessageHead() {
        return messageHead;
    }

    public void setMessageHead(MessageHead messageHead) {
        this.messageHead = messageHead;
    }

    public MessageBody getMessageBody() {
        return messageBody;
    }

    public void setMessageBody(MessageBody messageBody) {
        this.messageBody = messageBody;
    }

    public Integer getSerial(){
        return getNetMessageHead().getSerial();
    }

    public Integer getCmd(){
        return getNetMessageHead().getCmd();
    }

    public MessageHead getNetMessageHead() {
        return messageHead;
    }

    public MessageBody getNetMessageBody() {
        return messageBody;
    }
}

消息解码

/**
 * json转消息对象
 * @author : 钟满红
 */
public class JsonToMessageHandler extends SimpleChannelInboundHandler<String> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        ctx.fireChannelRead(JsonUtil.formJson(msg, NetMessage.class));
    }
}

消息分发

/**
 * 消息入口
 * @author : 钟满红
 */
public class NetMessageHandler extends SimpleChannelInboundHandler<NetMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, NetMessage msg) throws Exception {
        //todo 线程异步处理请求
    }
}

netty的channel初始化

/**
 * tcp
 *
 * @author : 钟满红
 */
public class TcpChannelInitializer extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        //半包解码器
        pipeline.addLast("lengthDecoder", new LengthFieldBasedFrameDecoder(1024 * 10, 0, 4, 0, 4));
        //半包编码器
        pipeline.addLast("lengthEncoder", new LengthFieldPrepender(4, false));
        //字符解码器
        pipeline.addLast("stringDecoder", new StringDecoder());
        //字符编码器
        pipeline.addLast("stringEncoder", new StringEncoder());
        //json转消息对象
        pipeline.addLast("jsonToMessage", new JsonToMessageHandler());
        //网络消息入口处理
        pipeline.addLast("messageHandler", new NetMessageHandler());

    }
}

netty服务组装

/**
 * 网络服务
 * @author : 钟满红
 */
public class NetService implements IService {

    private final NioEventLoopGroup boss = new NioEventLoopGroup(1);
    private final NioEventLoopGroup work = new NioEventLoopGroup();

    private ChannelFuture serverSocketFuture;
    @Override
    public void startup() throws Exception {
        int port = 8888;
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(boss, work).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .option(ChannelOption.SO_BACKLOG, 500)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childOption(ChannelOption.TCP_NODELAY, true)
                .childHandler(new TcpChannelInitializer());
        try {
            serverSocketFuture = bootstrap.bind(port).sync();
        } catch (Exception e) {
            shutdown();
        }
    }

    @Override
    public void shutdown() throws Exception {
        try {
            if (serverSocketFuture != null) {
                serverSocketFuture.channel().close().sync();
            }
        } catch (Exception e) {
        } finally {
            boss.shutdownGracefully();
            work.shutdownGracefully();
        }
    }
}

netty服务注入到Services

    /**
     * 网络服务
     */
    public static final NetService netService = valueOf(new NetService());

标签:Netty,java,网络服务,void,private,return,new,Integer,public
来源: https://blog.csdn.net/manREDoo/article/details/121853066

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有