Netty游戏服务器之四protobuf编解码和黏包处理

2024-03-08 22:48

本文主要是介绍Netty游戏服务器之四protobuf编解码和黏包处理,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

我们还没讲客户端怎么向服务器发送消息,服务器怎么接受消息。

 

在讲这个之前我们先要了解一点就是tcp底层存在粘包和拆包的机制,所以我们在进行消息传递的时候要考虑这个问题。

 

看了netty权威这里处理的办法:

我决定netty采用自带的半包解码器LengthDecoder()的类处理粘包的问题,客户端我是用这里的第三种思路。

消息的前四个字节是整个消息的长度,客户端接收到消息的时候就将前4个字节解析出来,然后再根据长度接收消息。

 

那么消息的编解码我用的是google的protobuf,这个在业界也相当有名,大家可以百度查查。不管你们用不用,反正我是用了。

 

在了解完之后,我们就来搭建这个消息编解码的框架(当然这个只是我个人的想法,可能有很多不好的地方,你们可以指正)

 

首先需要下载的是支持c#的protobuf-net插件,注意google官方的是不支持c#的。

 

http://pan.baidu.com/s/1eQdFTmU

 

打开压缩包,找到Full/Unity/protobuf-net.dll复制到我们的unity中。

 

在服务端呢,我用的是protobuff,这处理速度听说和原生的相差不大。

 

和之前的一样,吧这些jar包都添加到eclipse的build-path中。

 

好了,消息我服务器和客户端都写一个统一的协议SocketModel类,这样传送消息的时候就不会有歧义。

C#中:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using ProtoBuf;//注意要用到这个dll
[ProtoContract]
public class SocketModel{[ProtoMember(1)]private int type;//消息类型[ProtoMember(2)]private int area;//消息区域码[ProtoMember(3)]private int command;//指令[ProtoMember(4)]private List<string> message;//消息public SocketModel(){}public SocketModel(int type, int area, int command,List<string> message){this.type = type;this.area = area;this.command = command;this.message = message;}public int GetType(){return type;}public void SetType(int type){this.type = type;}public int GetArea(){return this.area;}public void SetArea(int area){this.area = area;}public int GetCommand(){return this.command;}public void SetCommand(int command){this.command = command;}public List<string> GetMessage(){return message;}public void SetMessage(List<string> message){this.message = message;}
}

  java中:

public class SocketModel {private int type;private int area;private int command;private List<String> message;public int getType() {return type;}public void setType(int type) {this.type = type;}public int getArea() {return area;}public void setArea(int area) {this.area = area;}public int getCommand() {return command;}public void setCommand(int command) {this.command = command;}public List<String> getMessage() {return message;}public void setMessage(List<String> message) {this.message = message;}
}

  好了,制定好协议后,我们来动手在服务器搞出点事情来。

首先,打个包com.netty.decoder,在里面我们创建我们的解码器类,LengthDecode和MessageDecode类

public class LengthDecoder extends LengthFieldBasedFrameDecoder{public LengthDecoder(int maxFrameLength, int lengthFieldOffset,int lengthFieldLength, int lengthAdjustment, int initialBytesToStrip) {super(maxFrameLength, lengthFieldOffset, lengthFieldLength, lengthAdjustment,initialBytesToStrip);}}

  这个功能你们可以去百度查,主要是吧接收到的二进制消息的前四个字节干掉。

public class MessageDecoder extends ByteToMessageDecoder{private Schema<SocketModel> schema = RuntimeSchema.getSchema(SocketModel.class);//protostuff的写法@Overrideprotected void decode(ChannelHandlerContext ctx, ByteBuf in,List<Object> obj) throws Exception {byte[] data = new byte[in.readableBytes()];in.readBytes(data);SocketModel message = new SocketModel();ProtobufIOUtil.mergeFrom(data, message, schema);obj.add(message);}}

  这个主要是吧接收的二进制转化成我们的协议消息SocketModel类型。

接着是编码器类,我们也打一个包,com.netty.encoder,里面创建一个MessageEncoder

在写这个之前我们写个工具类,com.netty.util,里面我么创建一个CoderUtil类,主要处理int和byte之间的转化。

 

public class CoderUtil {/*** 将字节转成整形* @param data* @param offset* @return*/public static int bytesToInt(byte[] data, int offset) {int num = 0;for (int i = offset; i < offset + 4; i++) {num <<= 8;num |= (data[i] & 0xff);}return num;}/*** 将整形转化成字节* @param num* @return*/public static byte[] intToBytes(int num) {   byte[] b = new byte[4];for (int i = 0; i < 4; i++) {b[i] = (byte) (num >>> (24 - i * 8));}return b;}}

  MessageEncoder:

public class MessageEncoder extends MessageToByteEncoder<SocketModel>{private Schema<SocketModel> schema = RuntimeSchema.getSchema(SocketModel.class);@Overrideprotected void encode(ChannelHandlerContext ctx, SocketModel message,ByteBuf out) throws Exception {//System.out.println("encode");LinkedBuffer buffer = LinkedBuffer.allocate(1024);byte[] data = ProtobufIOUtil.toByteArray(message, schema, buffer);ByteBuf buf = Unpooled.copiedBuffer(CoderUtil.intToBytes(data.length),data);//在写消息之前需要把消息的长度添加到投4个字节out.writeBytes(buf);}
}

  在写完这些编解码,我们需要将他们加到channel的pipeline中,

protected void initChannel(SocketChannel ch) throws Exception {ch.pipeline().addLast(new LengthDecoder(1024,0,4,0,4));ch.pipeline().addLast(new MessageDecoder());ch.pipeline().addLast(new MessageEncoder());ch.pipeline().addLast(new ServerHandler());}

  

 

————————————————————————服务器告一段落,接着写客户端————————————————————————————

在我们之前写的MainClient的代码中我们加入接收和发送消息的方法。

private byte[] recieveData;private int len;private bool isHead;void Start()
{if (client == null){Connect();}isHead = true;recieveData = new byte[800];client.GetStream().BeginRead(recieveData,0,800,ReceiveMsg,client.GetStream());//在start里面开始异步接收消息
}

  

public void SendMsg(SocketModel socketModel){byte[] msg = Serial(socketModel);//消息体结构:消息体长度+消息体byte[] data = new byte[4 + msg.Length];IntToBytes(msg.Length).CopyTo(data, 0);msg.CopyTo(data, 4);client.GetStream().Write(data, 0, data.Length);//print("send");}public void ReceiveMsg(IAsyncResult ar)//异步接收消息{NetworkStream stream = (NetworkStream)ar.AsyncState;stream.EndRead(ar);//读取消息体的长度if (isHead){byte[] lenByte = new byte[4];System.Array.Copy(recieveData,lenByte,4);len = BytesToInt(lenByte, 0);isHead = false;}//读取消息体内容if (!isHead){byte[] msgByte = new byte[len];System.Array.ConstrainedCopy(recieveData,4,msgByte,0,len);isHead = true;len = 0;message = DeSerial(msgByte);}stream.BeginRead(recieveData,0,800,ReceiveMsg,stream);}	private byte[] Serial(SocketModel socketModel)//将SocketModel转化成字节数组{using (MemoryStream ms = new MemoryStream()){Serializer.Serialize<SocketModel>(ms, socketModel);byte[] data = new byte[ms.Length];ms.Position= 0;ms.Read(data, 0, data.Length);return data;}}private SocketModel DeSerial(byte[] msg)//将字节数组转化成我们的消息类型SocketModel{using(MemoryStream ms = new MemoryStream()){ms.Write(msg,0,msg.Length);ms.Position = 0;SocketModel socketModel = Serializer.Deserialize<SocketModel>(ms);return socketModel;}}public static int BytesToInt(byte[] data, int offset){int num = 0;for (int i = offset; i < offset + 4; i++){num <<= 8;num |= (data[i] & 0xff);}return num;}public static byte[] IntToBytes(int num){byte[] bytes = new byte[4];for (int i = 0; i < 4; i++){bytes[i] = (byte)(num >> (24 - i * 8));}return bytes;}

  

就行告一段落,太长了不好,读者可能吃不消。但我不鄙视长不好,终究长还是最有用的 =_=!

转载于:https://www.cnblogs.com/CaomaoUnity3d/p/4610183.html

这篇关于Netty游戏服务器之四protobuf编解码和黏包处理的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/788662

相关文章

Python+FFmpeg实现视频自动化处理的完整指南

《Python+FFmpeg实现视频自动化处理的完整指南》本文总结了一套在Python中使用subprocess.run调用FFmpeg进行视频自动化处理的解决方案,涵盖了跨平台硬件加速、中间素材处理... 目录一、 跨平台硬件加速:统一接口设计1. 核心映射逻辑2. python 实现代码二、 中间素材处

Go异常处理、泛型和文件操作实例代码

《Go异常处理、泛型和文件操作实例代码》Go语言的异常处理机制与传统的面向对象语言(如Java、C#)所使用的try-catch结构有所不同,它采用了自己独特的设计理念和方法,:本文主要介绍Go异... 目录一:异常处理常见的异常处理向上抛中断程序恢复程序二:泛型泛型函数泛型结构体泛型切片泛型 map三:文

SpringBoot项目整合Netty启动失败的常见错误总结

《SpringBoot项目整合Netty启动失败的常见错误总结》本文总结了SpringBoot集成Netty时常见的8类问题及解决方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参... 目录一、端口冲突问题1. Tomcat与Netty端口冲突二、主线程被阻塞问题1. Netty启动阻

SpringSecurity中的跨域问题处理方案

《SpringSecurity中的跨域问题处理方案》本文介绍了跨域资源共享(CORS)技术在JavaEE开发中的应用,详细讲解了CORS的工作原理,包括简单请求和非简单请求的处理方式,本文结合实例代码... 目录1.什么是CORS2.简单请求3.非简单请求4.Spring跨域解决方案4.1.@CrossOr

requests处理token鉴权接口和jsonpath使用方式

《requests处理token鉴权接口和jsonpath使用方式》文章介绍了如何使用requests库进行token鉴权接口的处理,包括登录提取token并保存,还详述了如何使用jsonpath表达... 目录requests处理token鉴权接口和jsonpath使用json数据提取工具总结reques

Linux服务器数据盘移除并重新挂载的全过程

《Linux服务器数据盘移除并重新挂载的全过程》:本文主要介绍在Linux服务器上移除并重新挂载数据盘的整个过程,分为三大步:卸载文件系统、分离磁盘和重新挂载,每一步都有详细的步骤和注意事项,确保... 目录引言第一步:卸载文件系统第二步:分离磁盘第三步:重新挂载引言在 linux 服务器上移除并重新挂p

Apache服务器IP自动跳转域名的问题及解决方案

《Apache服务器IP自动跳转域名的问题及解决方案》本教程将详细介绍如何通过Apache虚拟主机配置实现这一功能,并解决常见问题,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,... 目录​​问题背景​​解决方案​​方法 1:修改 httpd-vhosts.conf(推荐)​​步骤

C# 空值处理运算符??、?. 及其它常用符号

《C#空值处理运算符??、?.及其它常用符号》本文主要介绍了C#空值处理运算符??、?.及其它常用符号,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面... 目录一、核心运算符:直接解决空值问题1.??空合并运算符2.?.空条件运算符二、辅助运算符:扩展空值处理

浅析Python中如何处理Socket超时

《浅析Python中如何处理Socket超时》在网络编程中,Socket是实现网络通信的基础,本文将深入探讨Python中如何处理Socket超时,并提供完整的代码示例和最佳实践,希望对大家有所帮助... 目录开篇引言核心要点逐一深入讲解每个要点1. 设置Socket超时2. 处理超时异常3. 使用sele

SpringMVC配置、映射与参数处理​入门案例详解

《SpringMVC配置、映射与参数处理​入门案例详解》文章介绍了SpringMVC框架的基本概念和使用方法,包括如何配置和编写Controller、设置请求映射规则、使用RestFul风格、获取请求... 目录1.SpringMVC概述2.入门案例①导入相关依赖②配置web.XML③配置SpringMVC