从零开始手写mmo游戏从框架到爆炸(七)— 消息封装

导航:从零开始手写mmo游戏从框架到爆炸(零)—— 导航-CSDN博客      

    上一篇,我们初步把消息handler 注册到了服务中,在进行后续工作之前我们需要再做一些准备工作。

        第一:把之前自己管理的bean放到spring中去管理,后面大部分的bean都通过spring来管理。

        第二:为了方便路由消费,我们要创建一个消息体方便byte字节数组传输。

Spring        

先把spring上下文变量工具整好

SpringContextHelper.java

package com.loveprogrammer.base.factory;import org.springframework.context.ApplicationContext;public class SpringContextHelper {private static ApplicationContext ac;public static void setApplicationContext(ApplicationContext ac) {SpringContextHelper.ac = ac;}public static ApplicationContext getContext() {return ac;}public static Object getBean(String name) {return ac.getBean(name);}public static Object getBean(Class clazz) {return ac.getBean(clazz);}}

CommonBootConfig.java

import com.loveprogrammer.base.factory.SpringContextHelper;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;@Configuration
public class CommonBootConfig implements ApplicationContextAware {@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {SpringContextHelper.setApplicationContext(applicationContext);}
}

修改 NetworkListener.java

@Component
public class NetworkListener implements INetworkEventListener {

 修改 TcpMessageStringHandler.java

@Component
public class TcpMessageStringHandler extends SimpleChannelInboundHandler<String> {private static final Logger logger = LoggerFactory.getLogger(TcpMessageStringHandler.class);@Autowiredprivate INetworkEventListener listener;//    public TcpMessageStringHandler(INetworkEventListener listener) {
//        this.listener = listener;
//    }

修改TcpServerStringInitializer.java

public class TcpServerStringInitializer extends ChannelInitializer<SocketChannel> {@Overrideprotected void initChannel(SocketChannel ch) {ChannelPipeline pipeline = ch.pipeline();pipeline.addLast("framer",new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));pipeline.addLast("decoder", new StringDecoder());pipeline.addLast("encoder", new StringEncoder());TcpMessageStringHandler handler = (TcpMessageStringHandler) SpringContextHelper.getBean(TcpMessageStringHandler.class);pipeline.addLast(handler);}}

 消息封装

创建一个类 StringMessage

package com.loveprogrammer.pojo;import com.alibaba.fastjson2.JSON;/*** @ClassName StringMessage* @Description string类型的请求的请求体* @Author admin* @Date 2024/1/31 10:35* @Version 1.0*/
public class StringMessage {/****         topicId 路由主键对应class*         tagId 路由副健,对应method*         statusC内容的长ode主要是返回内容是告诉客户端消息的状态,成功为1,其他不同的错误使用不同的错误码*         length是度,内容的长度是不可控制的,所以使用一个长度进行定义*         body是具体的内容*/private int topicId;private int tagId;private int statusCode;private int length;private String body;public StringMessage() {}//    public StringMessage(short messageId) {
//        this.messageId = messageId;
//    }public static StringMessage create(int topicId,int tagId) {StringMessage stringMessage = new StringMessage();stringMessage.setTopicId(topicId);stringMessage.setTagId(tagId);return stringMessage;}public static StringMessage create(String origin) {StringMessage stringMessage = JSON.parseObject(origin, StringMessage.class);return stringMessage;}public static StringMessage create(int length, int topicId,int tagId , int statusCode, String content) {return new StringMessage(length, topicId, tagId, statusCode, content);}private StringMessage(int length, int topicId,int tagId, int statusCode, String body) {this.length = length;this.topicId = topicId;this.tagId = tagId;this.statusCode = statusCode;this.body = body;}public int getTopicId() {return topicId;}public void setTopicId(int topicId) {this.topicId = topicId;}public int getTagId() {return tagId;}public void setTagId(int tagId) {this.tagId = tagId;}public int getStatusCode() {return statusCode;}public void setStatusCode(int statusCode) {this.statusCode = statusCode;}public int getLength() {return length;}public void setLength(int length) {this.length = length;}public String getBody() {return body;}public void setBody(String body) {this.body = body;}@Overridepublic String toString() {return "StringMessage{" + "messageId=" + topicId + ", statusCode=" + statusCode + ", length=" + length+ ", body='" + body + '\'' + '}';}
}

  创建两个编解码类 

  MessageDecoder.java

package com.loveprogrammer.codec;import com.loveprogrammer.constants.ConstantValue;
import com.loveprogrammer.pojo.StringMessage;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;/*** @ClassName MessageDecoder* @Description 消息解码器* @Author admin* @Date 2024/1/31 10:43* @Version 1.0*/
public class MessageDecoder extends LengthFieldBasedFrameDecoder {//判断传送客户端传送过来的数据是否按照协议传输,头部信息的大小应该是 int+int+int = 4+4+4 = 12private static final int HEADER_SIZE = 12;private int topicId;private int tagId;private int statusCode;private int length;private String body;/***** @param maxFrameLength 解码时,处理每个帧数据的最大长度* @param lengthFieldOffset 该帧数据中,存放该帧数据的长度的数据的起始位置* @param lengthFieldLength 记录该帧数据长度的字段本身的长度* @param lengthAdjustment 修改帧数据长度字段中定义的值,可以为负数* @param initialBytesToStrip 解析的时候需要跳过的字节数* @param failFast 为true,当frame长度超过maxFrameLength时立即报TooLongFrameException异常,为false,读取完整个帧再报异常*/public MessageDecoder(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength, int lengthAdjustment, int initialBytesToStrip, boolean failFast) {super(maxFrameLength, lengthFieldOffset, lengthFieldLength, lengthAdjustment, initialBytesToStrip, failFast);}@Overrideprotected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {if(in == null){return null;}if(in.readableBytes() < HEADER_SIZE) {throw new Exception("可读信息段比头部信息都小");}// 注意在读的过程中,readIndex的指针也在移动topicId = in.readInt();tagId = in.readInt();statusCode = in.readInt();length = in.readInt();if(in.readableBytes() < length) {throw new Exception("body获取长度" + length + ",实际长度没有达到");}ByteBuf buf = in.readBytes(length);byte[] req = new byte[buf.readableBytes()];buf.readBytes(req);body = new String(req, ConstantValue.PROJECT_CHARSET);StringMessage stringMessage = StringMessage.create(length, topicId, tagId, statusCode, body);return stringMessage;}
}

MessageEncoder.java

package com.loveprogrammer.codec;import com.loveprogrammer.constants.ConstantValue;
import com.loveprogrammer.pojo.StringMessage;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;import java.nio.charset.Charset;/*** @ClassName MessageEncoder* @Description 消息编码器* @Author admin* @Date 2024/1/31 10:40* @Version 1.0*/
public class MessageEncoder extends MessageToByteEncoder<StringMessage> {@Overrideprotected void encode(ChannelHandlerContext ctx, StringMessage msg, ByteBuf out) throws Exception {if(null == msg) {throw new Exception("msg is null");}String body = msg.getBody();byte[] bodyBytes = body.getBytes(Charset.forName(ConstantValue.PROJECT_CHARSET));out.writeInt(msg.getTopicId());out.writeInt(msg.getTagId());out.writeInt(msg.getStatusCode());out.writeInt(bodyBytes.length);out.writeBytes(bodyBytes);}
}

 下一章我们来实现byte数组传输数据

上一篇:从零开始手写mmo游戏从框架到爆炸(六)— 消息处理工厂-CSDN博客

全部源码详见:

gitee : eternity-online: 多人在线mmo游戏 - Gitee.com

分支:step-06

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/674535.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

c++设计模式之装饰器模式

作用 为现有类增加功能 案例说明 class Car { public:virtual void show()0; };class Bmw:public Car { public:void show(){cout<<"宝马汽车>>"<<endl;} };class Audi:public Car { public:void show(){cout<<"奥迪汽车>>&q…

三、设计模式相关理论总结

一、面向对象编程 1.1 概述 简称Object Oriented Program(OOP)&#xff0c;指以类或对象作为基础组织单元&#xff0c;遵循封装、继承、多态以及抽象等特性&#xff0c;进行编程。其中面向对象不一定遵循封装、继承、封装和多态等特性&#xff0c;只是前人总结的套路规范&…

嵌入式学习之Linux入门篇笔记——10,Linux连接档概念

配套视频学习链接&#xff1a;http://【【北京迅为】嵌入式学习之Linux入门篇】 https://www.bilibili.com/video/BV1M7411m7wT/?p4&share_sourcecopy_web&vd_sourcea0ef2c4953d33a9260910aaea45eaec8 目录 1.Linux 下的连接档种类 2.什么是 inode&#xff1f; 3.什…

下一个排列_题解

【题解提供者】史青山 解法 思路 此题属于找规律题&#xff0c;我们可以把一个序列的全排列写出来&#xff0c;然后对比找规律&#xff0c;比如序列 1 2 3 4 5&#xff0c;全排列如下&#xff1a; 1 2 3 4 5 1 2 3 5 4 1 2 4 3 5 1 2 4 5 3 1 2 5 3 4 1 2 5 4 3 1 3 2 4 5 1…

ssh使用密钥远程连接问题排查

ssh使用密钥远程连接时&#xff0c;会因为各项原因导致无法连接 本文以本机(windows), 连接目标机(Ubuntu) 为例&#xff0c; 列出应该逐项排查的问题&#xff0c; 确保能够正确连接 1. 确保两机器能够相互ping通 windows和linux都有防火墙&#xff0c; 双方ping不同大概率是因…

7、7 个适合初学者的项目,让您开始使用 ChatGPT

7 个适合初学者的项目,让您开始使用 ChatGPT 在当今世界释放人工智能的力量。 在技术以前所未有的速度发展的时代,人工智能?—?或朋友🤓的人工智能脱颖而出,成为最具变革性的力量之一。 从自动化日常任务到预测复杂模式,人工智能正在重塑行业并重新定义可能性。 当我…

Unity2D 学习笔记 0.Unity需要记住的常用知识

Unity2D 学习笔记 0.Unity需要记住的常用知识 前言调整Project SettingTilemap相关&#xff08;创建地图块&#xff09;C#脚本相关程序运行函数private void Awake()void Start()void Update() Collider2D碰撞检测private void OnTriggerStay2D(Collider2D player)private void…

【Algorithms 4】算法(第4版)学习笔记 06 - 2.3 快速排序

文章目录 前言参考目录学习笔记1&#xff1a;基本算法1.1&#xff1a;快速排序 demo 演示1.2&#xff1a;快速排序切分代码实现1.3&#xff1a;实现细节1.4&#xff1a;案例分析1.4.1&#xff1a;最佳案例1.4.2&#xff1a;最坏案例1.4.3&#xff1a;平均案例分析1.5&#xff1…

【MySQL】学习和总结DCL的权限控制

&#x1f308;个人主页: Aileen_0v0 &#x1f525;热门专栏: 华为鸿蒙系统学习|计算机网络|数据结构与算法 ​&#x1f4ab;个人格言:“没有罗马,那就自己创造罗马~” #mermaid-svg-Bl9kYeLf8GfpdQgL {font-family:"trebuchet ms",verdana,arial,sans-serif;font-siz…

消息队列MQ 介绍

&#x1f47d;System.out.println(“&#x1f44b;&#x1f3fc;嗨&#xff0c;大家好&#xff0c;我是代码不会敲的小符&#xff0c;双非大四&#xff0c;Java实习中…”); &#x1f4da;System.out.println(“&#x1f388;如果文章中有错误的地方&#xff0c;恳请大家指正&a…

Vue-56、Vue技术路由的使用

路由 1、理解&#xff1a;一个路由&#xff08;route&#xff09;就是一种映射关系&#xff08;key-value&#xff09;&#xff0c;多个路由需要路由器&#xff08;router&#xff09;进行管理。 2、前端路由&#xff1a;key是路径&#xff0c;value是组件 1、基本使用 vue…

JFinal中如何实现反序列化----JSON字符串向Model对象转换

需求: 将客户端传来的requestbody反序列化成对应的Model对象。 一、反序列化--驼峰命名 1、fastjson实现 JFinal中没有提供反序列化的方法&#xff0c;因为大多数情况下&#xff0c;可以直接通过jar包进行转换&#xff0c;如利用fastjson&#xff0c;我们可以通过如下方式进行…

Renitialized existing Git repositoy in D:/libai/project/gitab-cicd-test/.git/

天行健&#xff0c;君子以自强不息&#xff1b;地势坤&#xff0c;君子以厚德载物。 每个人都有惰性&#xff0c;但不断学习是好好生活的根本&#xff0c;共勉&#xff01; 文章均为学习整理笔记&#xff0c;分享记录为主&#xff0c;如有错误请指正&#xff0c;共同学习进步。…

vue 引入 百度地图API 和 路书

公司项目中&#xff0c;偶尔都会涉及到地图的使用&#xff0c;这里以百度地图为例&#xff0c;我们梳理一下引用流程及注意点 账号和获取密钥 百度地图示例 百度地图 类参考 1、账号和获取密钥 // api.map.baidu.com/api?typewebgl&v3.0&ak您的密钥<script type…

1899_野火FreeRTOS教程阅读笔记_任务创建

1899_野火FreeRTOS教程阅读笔记_任务创建 全部学习汇总&#xff1a; g_FreeRTOS: FreeRTOS学习笔记 (gitee.com) 关于这部分&#xff0c;从一般前后台程序到RTOS的任务描述了很多。但是我觉得这本书的这部分描述没有描述到关键的信息点。其实&#xff0c;RTOS存在的一个主要的目…

机器学习系列——(十七)聚类

引言 在当今数据驱动的时代&#xff0c;机器学习已经成为了解锁数据潜能的关键技术之一。其中&#xff0c;聚类作为机器学习领域的一个重要分支&#xff0c;广泛应用于数据挖掘、模式识别、图像分析等多个领域。本文旨在深入探讨聚类技术的原理、类型及其应用&#xff0c;为读…

【Flink入门修炼】1-3 Flink WordCount 入门实现

本篇文章将带大家运行 Flink 最简单的程序 WordCount。先实践后理论&#xff0c;对其基本输入输出、编程代码有初步了解&#xff0c;后续篇章再对 Flink 的各种概念和架构进行介绍。 下面将从创建项目开始&#xff0c;介绍如何创建出一个 Flink 项目&#xff1b;然后从 DataStr…

IDEA创建Java类时自动添加注释(作者、年份、月份)

目录 IDEA创建Java类时自动添加注释&#xff08;作者、年份、月份&#xff09;如图&#xff1a; IDEA创建Java类时自动添加注释&#xff08;作者、年份、月份&#xff09; 简单记录下&#xff0c;IDEA创建Java类时自动添加注释&#xff08;作者、年份、月份&#xff09;&#…

Java+微信小程序实现智慧家政系统 JAVA+Vue+SpringBoot+MySQL

目录 一、摘要1.1 项目介绍1.2 项目录屏 二、功能模块三、系统展示四、核心代码4.1 查询家政服务4.2 新增单条服务订单4.3 新增留言反馈4.4 小程序登录4.5 小程序数据展示 五、免责说明 一、摘要 1.1 项目介绍 基于微信小程序JAVAVueSpringBootMySQL的智慧家政系统&#xff0…

【SparkML实践7】特征选择器FeatureSelector

本节介绍了用于处理特征的算法&#xff0c;大致可以分为以下几组&#xff1a; 提取&#xff08;Extraction&#xff09;&#xff1a;从“原始”数据中提取特征。转换&#xff08;Transformation&#xff09;&#xff1a;缩放、转换或修改特征。选择&#xff08;Selection&…