C#使用ProtoBuf进行Socket通信
2017-10-31 22:19
751 查看
//添加特性,表示可以被ProtoBuf工具序列化 [ProtoContract] class MessageModel { //添加特性,表示该字段可以被序列化,1可以理解为下标 [ProtoMember(1)] public int ID { get; set; } [ProtoMember(2)] public string Name { get; set; } [ProtoMember(3)] public string Message { get; set; } }
/// <summary> /// 将消息序列化为二进制的方法 /// </summary> /// <param name="meg">要序列化的对象</param> /// <returns></returns> public byte[] Serizlize(MessageModel meg) { try { //涉及格式转换,需要用到流,将二进制序列化到流中 using (MemoryStream ms=new MemoryStream()) { //使用ProtoBuf工具的序列化方法 ProtoBuf.Serializer.Serialize<MessageModel>(ms, meg); //定义二级制数组,保存序列化后的结果 byte[] result = new byte[ms.Length]; //将流的位置设为0,起始点 //ms.Seek(0, SeekOrigin.Begin); ms.Position = 0; //将流中的内容读取到二进制数组中 ms.Read(result, 0, result.Length); return result; } } catch (Exception ex) { Debug.Write("序列化失败: " + ex.ToString()); return null; } } /// <summary> /// 将收到的消息反序列化成对象 /// </summary> /// <param name="msg">收到的消息</param> /// <returns></returns> public MessageModel DeSerizlize(byte[] msg) { try { using(MemoryStream ms=new MemoryStream()) { //将消息写入流中 ms.Write(msg, 0, msg.Length); //将流的位置归0 ms.Position = 0; //使用工具反序列化对象 MessageModel mm = ProtoBuf.Serializer.Deserialize<MessageModel>(ms); return mm; } } catch (Exception ex) { Debug.Write("反序列化失败: " + ex.ToString()); return null; } }
/// <summary> /// 通过socket发送数据data /// </summary> private void Send(Socket socket, string data) { if (socket != null && data != null && !data.Equals("")) { // byte[] bytes = Encoding.UTF8.GetBytes(data); // 将data转化为byte数组 //构建序列化需要的结构 MessageModel mm = new MessageModel(); mm.ID = 1; mm.Name = "张三"; mm.Message = data; //序列化数据 Proto proto = new Proto(); byte[] bytes = proto.Serizlize(mm); socket.Send(bytes); // } }
/// <summary> /// 从socket接收数据 /// </summary> private string Receive(Socket socket) { string data = ""; byte[] bytes = null; int len = socket.Available; if (len > 0) { bytes = new byte[len]; int receiveNumber = socket.Receive(bytes); // data = Encoding.UTF8.GetString(bytes, 0, receiveNumber); Proto pf = new Proto(); //反序列化数据 MessageModel mm= pf.DeSerizlize(bytes); data = mm.ID + "\r\n" + mm.Name + "\r\n" + mm.Message; } return data; }
相关文章推荐
- C#使用Protocol Buffer(ProtoBuf)进行Unity中的Socket通信
- C#使用ProtocolBuffer(ProtoBuf)进行Unity中的Socket通信
- C#使用Protocol Buffer(ProtoBuf)进行Unity中的Socket通信
- C#使用Protocol Buffer(ProtoBuf)进行Unity中的Socket通信
- C#使用Protocol Buffer(ProtoBuf)进行Unity中的Socket通信
- C#使用Protocol Buffer(ProtoBuf)进行对象的序列化与反序列化
- C# 使用 protobuf 进行对象序列化与反序列化
- 【转载】android与PC,C#与Java 利用protobuf 进行无障碍通讯【Socket】
- Android与PC,C#与Java 利用protobuf 进行无障碍通讯【Socket】
- c#序列化与反序列化通用方法, 使用protobuf-net实现
- C#下使用protobuf(Google Protocol Buffers)
- VS下使用Google Protobuf完成SOCKET通信
- 在Javascript中使用protobuf与c++进行通信
- C#下使用protobuf(Google Protocol Buffers)
- protobuf在C#项目中的使用
- 在Javascript中使用protobuf与c++进行通信
- 使用protobuf进行与Java通信
- Android与PC,C#与Java 利用protobuf 进行无障碍通讯【Socket】
- 【protobuf】 3.使用protobuf-csharp-port进行序列化和反序列化
- erlang中使用google protobuf进行通信