search
HomeBackend DevelopmentC#.Net TutorialSocket transmission protobuf byte stream example tutorial
Socket transmission protobuf byte stream example tutorialJun 23, 2017 pm 04:15 PM
protobufsocketunitytransmissionexplorer

Copyright Statement: This article is an original article, please declare when reprinting

I am currently working on a chess and card project, and I need to use socket to transmit protobuf byte stream. I found some blogs and After reading the article, I found that it was not particularly comprehensive, so I took out all the source code I researched and shared it with everyone. Because I just started doing it, there may be shortcomings. Welcome to comment~~

This article is mainly about Serialization and parsing of protocol buffer files, without further ado, let’s go straight to the practical information

 1 /// <summary> 2 /// 将消息序列化为二进制的方法 3 /// </summary> 4 /// <param>要序列化的对象 5 public static byte[] Serialize(IExtensible model) 6 { 7   try 8   { 9     //创建流对象10     MemoryStream ms = new MemoryStream()11     //使用ProtoBuf自带的序列化工具序列化IExtensible对象12     Serializer.Serialize<iextensible>(ms, model);13     //创建二级制数组,保存序列化后的流14     byte[] bytes = new byte[ms.Length];15     //将流的位置设为016     ms.Position = 0;17     //将流中的内容读取到二进制数组中18     ms.Read(bytes, 0, bytes.Length);19     return bytes;20   }21   catch (Exception e)22   {23     Debug.Log("序列化失败: " + e.ToString());24     return null;25   }26 }</iextensible>

Each message in the protobuf file can be converted into c# through the ProtoGen tool provided by protocol buffer For example,

message Test {
    required string test1= 1;
    required string test2= 2;
}

will become

 1   [global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"SedReq")] 2   public partial class Test : global::ProtoBuf.IExtensible 3   { 4     public Test() {} 5      6     private string _test1; 7     [global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"test1", DataFormat = global::ProtoBuf.DataFormat.Default)] 8     public string test1 9     {10       get { return _test1; }11       set { _test1 = value; }12     }    
13     private string _test2;14     [global::ProtoBuf.ProtoMember(2, IsRequired = true, Name=@"test2", DataFormat = global::ProtoBuf.DataFormat.Default)]15     public string test216     {17       get { return _test2; }18       set { _test2 = value; }19     }20     private global::ProtoBuf.IExtension extensionObject;21     global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)22       { return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }23   }

after transformation. Ignore all codes with global, you will find that the transformation The resulting C# class is exactly the same as a standard C# entity class, and these converted classes inherit from ProtoBuf.IExtensible, so the type of the parameters of the serialization function above is IExtensible

with serialization , of course, deserialization is also required, that is, byte[] is deserialized into an object of a type inherited from IExtensible

 1     /// <summary> 2     /// 将收到的消息反序列化成IExtensible对象 3     /// </summary> 4     /// <param>收到的消息的字节流. 5     /// <returns></returns> 6     public static T DeSerialize<t>(byte[] bytes) where T : IExtensible 7     { 8         try 9         {10             MemoryStream ms = new MemoryStream()11             //将消息写入流中12             ms.Write(bytes, 0, bytes.Length);13             //将流的位置归014             ms.Position = 0;15             //反序列化对象16             T result = Serializer.Deserialize<t>(ms);17             return result;18         }19         catch (Exception e)20         {21             Debug.Log("反序列化失败: " + e.ToString());22             return null;23         }24     }</t></t>

Because the deserialized object is inherited from IExtensible Class object, so the return value must be defined using generic constraints, so as to ensure the versatility of the function

After the tool is done, the next step is to test the code

1     public void Test()2     {3         Test test = new Test() { test1 = "123", test2 = "456" };4         byte[] bytes = Serialize(test);5         Test test2 = DeSerialize<test>(bytes);6         Debug.Log(test2.test1 + test2.test2);7     }</test>

Output result 123456

Attached protobuf-net.dll file


Precompilation and conversion tool


The above is the detailed content of Socket transmission protobuf byte stream example tutorial. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP+Socket系列之IO多路复用及实现web服务器PHP+Socket系列之IO多路复用及实现web服务器Feb 02, 2023 pm 01:43 PM

本篇文章给大家带来了关于php+socket的相关知识,其中主要介绍了IO多路复用,以及php+socket如何实现web服务器?感兴趣的朋友下面一起来看一下,希望对大家有帮助。

Python的socket与socketserver怎么使用Python的socket与socketserver怎么使用May 28, 2023 pm 08:10 PM

一、基于TCP协议的socket套接字编程1、套接字工作流程先从服务器端说起。服务器端先初始化Socket,然后与端口绑定(bind),对端口进行监听(listen),调用accept阻塞,等待客户端连接。在这时如果有个客户端初始化一个Socket,然后连接服务器(connect),如果连接成功,这时客户端与服务器端的连接就建立了。客户端发送数据请求,服务器端接收请求并处理请求,然后把回应数据发送给客户端,客户端读取数据,最后关闭连接,一次交互结束,使用以下Python代码实现:importso

怎么使用Spring Boot+Vue实现Socket通知推送怎么使用Spring Boot+Vue实现Socket通知推送May 27, 2023 am 08:47 AM

SpringBoot端第一步,引入依赖首先我们需要引入WebSocket所需的依赖,以及处理输出格式的依赖com.alibabafastjson1.2.73org.springframework.bootspring-boot-starter-websocket第二步,创建WebSocket配置类importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Config

php socket无法连接怎么办php socket无法连接怎么办Nov 09, 2022 am 10:34 AM

php socket无法连接的解决办法:1、检查php是否开启socket扩展;2、打开php.ini文件,检查“php_sockets.dll”是否被加载;3、取消“php_sockets.dll”的注释状态即可。

unity发布出来的安卓apk该如何加密unity发布出来的安卓apk该如何加密May 13, 2023 am 11:10 AM

Unity3D程序的安全问题代码安全问题Unity3D程序的核心程序集文件Assembly-CSharp.dll是标准的.NET文件格式,附带了方法名、类名、类型定义等丰富的元数据信息,使用DnSpy等工具可以轻易地将其反编译和篡改,代码逻辑、类名和方法名等一览无余。代码逻辑一但被反编译,很容易滋生各种类型的外挂,破坏游戏平衡,如果代码逻辑中存在漏洞,也容易被挖掘和利用,可能对开发商造成无法预料的损失。资源安全问题Unity3D程序在编译打包阶段会通过Unity编辑器将资源打包成AssetBun

C#中常见的网络通信和安全性问题及解决方法C#中常见的网络通信和安全性问题及解决方法Oct 09, 2023 pm 09:21 PM

C#中常见的网络通信和安全性问题及解决方法在当今互联网时代,网络通信已经成为了软件开发中必不可少的一部分。在C#中,我们通常会遇到一些网络通信的问题,例如数据传输的安全性、网络连接的稳定性等。本文将针对C#中常见的网络通信和安全性问题进行详细讨论,并提供相应的解决方法和代码示例。一、网络通信问题网络连接中断:网络通信过程中,可能会出现网络连接的中断,这会导致

利用PHP和Socket实现实时文件传输技术研究利用PHP和Socket实现实时文件传输技术研究Jun 28, 2023 am 09:11 AM

随着互联网的发展,文件传输成为人们日常工作和娱乐中不可或缺的一部分。然而,传统的文件传输方式如邮件附件或文件分享网站存在一定的限制,无法满足实时性和安全性的需求。因此,利用PHP和Socket技术实现实时文件传输成为了一种新的解决方案。本文将介绍利用PHP和Socket技术实现实时文件传输的技术原理、优点和应用场景,并通过具体案例来演示该技术的实现方法。技术

PHP+Socket系列之实现客户端与服务端数据传输PHP+Socket系列之实现客户端与服务端数据传输Feb 02, 2023 am 11:35 AM

本篇文章给大家带来了关于php+socket的相关知识,其中主要介绍了什么是socket?php+socket如何实现客户端与服务端数据传输?感兴趣的朋友下面一起来看一下,希望对大家有帮助。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function