Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of protobuf Byte Stream transmitted by socket

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces the socket transmission protobuf byte stream example analysis, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.

Use multithreading to send and receive messages

/ / create message data model 2 id+ / in a formal project, the message structure is generally message length + message body content 3 public class Message 4 {public IExtensible protobuf; public int messageId; 7} 8 9 public class SocketClientTemp: MonoBehaviour 10 {11 const int packageMaxLength = 1024; 12 13 Socket mSocket; 14 Thread threadSend; 15 Thread threadRecive; 16 Queue allMessages = new Queue (); 17 Queue sendQueue = new Queue () Public bool Init () 20 {21 / / create a socket object 22 mSocket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 23 return SocketConnection ("here is ip", 1111); 24} 25 26 void Update () 27 {28 AnalysisMessage () 29} 30 31 / / 32 / / establish the ip address of the server connection 33 / / 34 / Port 36 bool SocketConnection (string ip, int port) 37 {38 try 39 {40 IPEndPoint ipep = new IPEndPoint (IPAddress.Parse (ip), port) 41 / / synchronous connection to the server. Asynchronous connection is recommended for practical use. The handling method will be 42 mSocket.Connect (ipep) in the next article on disconnected reconnection; 43 / / after the connection is successful, create two threads to send and receive messages 44 threadSend = new Thread (new ThreadStart (SendMessage)); 45 threadSend.Start () 46 threadRecive = new Thread (new ThreadStart (ReceiveMessage)); 47 threadRecive.Start (); 48 return true; 49} 50 catch (Exception e) 51 {52 Debug.Log (e.ToString ()); 53 Close (); 54 return false; 55}} # region. Send message 59 / / 60 / add data to send queue 61 / 62 / 63 / 64 public void AddSendMessageQueue (IExtensible protobufModel, int messageId) 65 {66 sendQueue.Enqueue (BuildPackage (protobufModel, messageId)) 67} void SendMessage () 70 {71 / / get the first data in the send queue and send it to server 72 while (true) 73 {74 if (sendQueue.Count = = 0) 75 {76 Thread.Sleep (100); 77 continue 78} 79 if (! mSocket.Connected) 80 {81 Close (); 82 break; 83} 84 else 85 Send (sendQueue.Peek ()) / / the first data in the sending queue 86} 87} 88 89 void Send (byte [] bytes) 90 {91 try 92 {93 mSocket.Send (bytes, SocketFlags.None); 94 / after the message is sent successfully, the sent message is removed from the sending queue 95 sendQueue.Dequeue () 96} 97 catch (SocketException e) 98 {99 / / if the error code is 10035, the server cache is full, so wait 100 milliseconds to send 100 if (e.NativeErrorCode = = 10035) 101 {102 Thread.Sleep (100); 103 Send (bytes) 1010105else106 Debug.Log (e.ToString ()), 1010101010 # endregion110 1111region. Parse the received void AnalysisMessage () 116 {117 while (allMessages.Count > 0) 118 {119 int id = allMessages.Dequeue () .messageId 120 switch (id) 121 {122 / / different processing based on message id 123} 124} 125} 126 127 / 130 void ReceiveMessage () 131 {132 while (true) 133 {134 if ( ! mSocket.Connected) 135 break 136 byte [] recvBytesHead = GetBytesReceive (4); 137 int bodyLength = IPAddress.NetworkToHostOrder (BitConverter.ToInt32 (recvBytesHead, 0)); 138 byte [] recvBytesBody = GetBytesReceive (bodyLength); 139 140 byte [] messageId = new byte [4]; 141 Array.Copy (recvBytesBody, 0, messageId, 0,4); 142byte [] messageBody = new byte [bodyLength-4] 144Array.Copy (recvBytesBody, 4, messageBody, 0, bodyLength-4); 144145 if (BitConverter.IsLittleEndian) 146Array.Reverse (messageId); 147FillAllPackages (BitConverter.ToInt32 (messageId, 0), messageBody) Populate the receiving message queue (int messageId, byte [] messageBody) 157{ 158switch (messageId) 159 {160 / / process messages according to message id And add to the receiving message queue 161case 1vig 162 allMessages.Enqueue (new Message () 163{ 164protobuf = ProtobufSerilizer.DeSerialize (messageBody), 165messageId = messageId 166}) 170171 / / 17717 / / 170171 / / 17717 / 176 byte [] GetBytesReceive (int length) 177 {178byte [] recvBytes = new byte [length]; 179 while (length > 0) 180 {181byte [] receiveBytes = new byte [length]

< packageMaxLength ? length : packageMaxLength];182 int iBytesBody = 0;183 if (length >

= receiveBytes.Length) 184iBytesBody = mSocket.Receive (receiveBytes, receiveBytes.Length, 0); 185else186 iBytesBody = mSocket.Receive (receiveBytes, length, 0); 187receiveBytes.CopyTo (recvBytes, recvBytes.Length-length); 188length-= iBytesBody;189} 190 return recvBytes 191} 192 # endregion193 194 / / 195 / build message packet 196 / / 197 / / 198 / / 199 byte [] BuildPackage (IExtensible protobufModel, int messageId) 200 {201 byte [] bbot 202 if (protobufModel! = null) 203b = ProtobufSerilizer.Serialize (protobufModel); 204else205 b = new byte [0] Message length (int data, length 4) + message id (int data, length 4) + message body content 207ByteBuffer buf = ByteBuffer.Allocate (b.Length + 4 + 4); 208 / / message length = message body content length + message id length 209buf.WriteInt (b.Length + 4); 210buf.WriteInt (messageId) 211212 if (protobufModel! = null) 213 buf.WriteBytes (b); 214 return buf.GetBytes (); 215} 216217 void OnDestroy () 218 {219 / / if socket multithreading is not turned off, unity will jam 220 Close () when running again. 221} 2222223 / / 224 / / close socket, terminate thread 225 / 226 public void Close () 227 {228 if (mSocket! = null) 229 {230 / / Microsoft officially recommends shutdown before shutting down socket, but after testing, it is found that the network is disconnected Shutdown will not be able to execute 231 if (mSocket.Connected) 232 mSocket.Shutdown (SocketShutdown.Both) 234 mSocket = null;235} 236 / / close thread 237 if (threadSend! = null) 238 threadSend.Abort (); 239 if (threadRecive! = null) 240 threadRecive.Abort (); 241 threadSend = null;242 threadRecive = null;243} 244}

At this point, the sending and receiving of messages using socket is basically over.

Thank you for reading this article carefully. I hope the article "sample Analysis of socket Transmission protobuf Byte flow" shared by the editor will be helpful to you. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report