服务器 datalen+Message----->PackageData------>网络传输([]byte)----->客户端---->UnPackageData---->datalen+Message
用Soket写网络程序,需要自己定制协议。
{len+data} len 解析出来的是data数据的长度,data 解析出来的是想要传输的数据
服务器上的Message
客户端的Message
需要注意的是客户端Message的字段命名需要和服务端的json标签保持一直。否则服务端解析json会丢失字段(这个bug我找了一个晚上加一个早上)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; [Serializable] public class Message { public string execute_type; public string struct_name; public string data; } class util { /// <summary> /// 包装数据 /// </summary> /// <param name="data"></param> /// <param name="exeCuteType"></param> /// <param name="className"></param> public static byte[] PackageData(object data,string exeCuteType,string className) { string jsonData = JsonConvert.SerializeObject(data); //byte[] byteData = Encoding.UTF8.GetBytes(jsonStr); Message message = new Message(); message.struct_name = className; message.data = jsonData; message.execute_type = exeCuteType; byte[] byteData =Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message)); Int32 len = byteData.Length; byte[] lenData = BitConverter.GetBytes(len); byte[] finalData = new byte[lenData.Length + byteData.Length]; lenData.CopyTo(finalData, 0); byteData.CopyTo(finalData, 4); return finalData; } /// <summary> /// 拆分数据 /// </summary> /// <param name="data"></param> /// <returns></returns> public static Message UnPackageData(byte[] data) { Int32 len = BitConverter.ToInt32(data, 0); System.Console.WriteLine(len); byte[] strByte = new byte[len]; Array.Copy(data,4,strByte,0,len); Message message = JsonConvert.DeserializeObject<Message>(Encoding.UTF8.GetString(strByte)); return message; } }
//没有go?? //包装数据 func PackageData(data interface{},executeType string,structType string)[]byte{ dataByte,err:=json.Marshal(&data) if err!=nil{ config.Logger.Fatalln("解析出错",err) } strJson:=string(dataByte) msg:=Message{} msg.ExecuteType=executeType msg.Data=strJson msg.StructName=structType finalData,err:=json.Marshal(&msg) if err!=nil{ log.Fatalln("解析失败",err) } var lenByte =make([]byte,4) length:=uint32(len(finalData)) binary.LittleEndian.PutUint32(lenByte,length) allData:=[][]byte{lenByte,finalData} newData:=bytes.Join(allData,[]byte("")) return newData } //解析数据 func UnPackageData(data []byte)(Message, error){ //println("总长度=:",len(data)) mes:=Message{} //utf8. byteBuffer:=bytes.NewBuffer(data[0:4]) var dataLen int32 err:=binary.Read(byteBuffer,binary.LittleEndian,&dataLen)//binary.BigEndian.Uint32(data[:4]) if err!=nil{ config.Logger.Println(err) } err=json.Unmarshal(data[4:4+dataLen],&mes) if err!=nil{ fmt.Println("解析失败",err) } return mes,err }
原文地址:https://www.cnblogs.com/Jokerlearn/p/10929818.html
时间: 2024-10-10 06:04:02