An example of socket transmission PROTOBUF byte stream

Source: Internet
Author: User
The previous article on the processing of data, this article mainly on the use of multithreading to send and receive messages

Create a message data Model 2//a formal project, the structure of the message is generally message length + message id+ message body Content 3 public class message 4 {public iextensible protobuf;  public int messageId; 7} 8 9 public class Socketclienttemp:monobehaviour {one const int packagemaxlength = 1024x768; Socke T Msocket; Threadsend Thread; Thread threadrecive; queue<message> allmessages = new queue<message> ();  queue<byte[]> sendqueue = new queue<byte[]> (); public bool Init () 20 {21//Create a Socket object msocket = new socket (AddressFamily.InterNetwork, Sock Ettype.stream, PROTOCOLTYPE.TCP); SocketConnection return ("Here is IP", 1111);     () () {analysismessage (); +//<summary> 32 Establishing a server connection//</summary>//<param name= IP > server IP address </param>//<param N Ame= "Port" > Port </param> socketconnection bool (string IP, int port)PNS {IPEndPoint Ipep = new IPEndPoint (Ipaddress.parse (IP), port); 41 Synchronous connection to the server, the actual use of the recommended use of asynchronous connection, processing method will be in the next thread of the reconnection when the Msocket.connect (IPEP); 43//After a successful connection, create two threads, respectively, for sending and receiving messages, Threadsend = new Thread (new ThreadStart (SendMessage)); Threadsend.start (); threadrecive = new Thread (new ThreadStart (ReceiveMessage)); Threadrecive.start (); return true;  (Exception e) {Debug.Log (e.tostring ()), and Close (); The return false; #region ... Send Message///<summary> 60//Add data to send queue///</summary>//<param name= "Protobufmode L "></param>//<param name=" messageId "></param> public void Addsendmessagequeue (Iexte       nsible Protobufmodel, int messageId) 65 {66  Sendqueue.enqueue (Buildpackage (Protobufmodel, messageId));             SendMessage} void () 70 {71//loop Gets the first data in the Send queue and then sends to the server (true) 73 {74             if (Sendqueue.count = = 0) (thread.sleep), continue; 78 } if (!msocket.connected) {Bayi Close (); 8     3} (Sendqueue.peek ());//Send Queue First Data 86} 87} 88 89              void Send (byte[] bytes) ({msocket.send try) (bytes, socketflags.none); 94 After the send is successful, the sent message is removed from the Send Queue sendqueue.dequeue ();              (SocketException e) 98 {99//If the error code is 10035, the server buffer is full, so wait 100 milliseconds to send again 100 if (E.nativeerrorcode = = 10035) 101 {102 Thread.Sleep (+); 103 Send   (bytes); 104           }105 else106 Debug.Log (e.tostring ()) 107}108}109 #endregion110 1 One-#region ...          Receive Message <summary>113/////Parse received message//</summary>115 void Analysismessage () 116 {117              while (Allmessages.count > 0) 118 {119 int id = allmessages.dequeue (). messageid;120 Switch (ID) 121 {122//do different processing according to the message ID 123}124}125}126 127/ &LT;SUMMARY&GT;128///Receive data 129//</summary>130 void ReceiveMessage () 131 {while (tr UE) 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 byte[] messageId = new byte[4];14    1          Array.copy (recvbytesbody, 0, messageId, 0, 4); 142 byte[] MessageBody = new byte[bodylength-4];143 Array.copy (Recvbytesbody, 4, messagebody, 0, bodyLength-4); 144 145 if (Bitconverter.islittlee Ndian) 146 array.reverse (MESSAGEID); 147 Fillallpackages (Bitconverter.toint32 (messageId, 0), M Essagebody); 148}}//<summary>152//Populate Receive Message Queue 153///</summary>154//< param name= "messageId" ></param>155//<param name= "MessageBody" ></param>156 void Fillallpack Ages (int messageId, byte[] messagebody) 157 {158 switch (MESSAGEID) 159 {160//messages are processed based on the message ID and added                     Add to Receive Message Queue 161 case 1:162 Allmessages.enqueue (New message () 163 {164 Protobuf = protobufserilizer.deserialize<testtemp> (messagebody), 165 messageId = message Id 166}); 167 break;168}169}170 171//<summary>172//Receive data and process 173//</summa ry>174//<param name= "Length" ></param>175//<returns></returns>176 byte[] GetBy         tesreceive (int length) 177 {178 byte[] recvbytes = new byte[length];179 while (length > 0) 180             {181 byte[] receivebytes = new Byte[length < packagemaxlength? length:packagemaxlength];182 int ibytesbody = 0;183 if (length >= receivebytes.length) 184 ibytesbody = Msocket.receive (Receivebytes, receivebytes.length, 0); 185 else186 ibytesbody = msocket.receive (Receivebytes, length, 0); 187 receivebytes.copyto (Recvbytes, recvbytes.length-length); 188 Length-= ibytesbody;      189}190 return recvbytes;191}192 #endregion193 194//<summary>195//Build message Packet 196 </summary> 197//<param name= "Protobufmodel" ></param>198//<param name= "MessageId" ></param>199 Byte[] Buildpackage (iextensible protobufmodel, int messageId) + (201 byte[] b;202 if (protobufmode L! = null) 203 b = Protobufserilizer.serialize (Protobufmodel); 204 else205 B = new byte[0];2 06//Message length (int data, length 4) + Message ID (int data, length 4) + Message body content 207 Bytebuffer buf = bytebuffer.allocate (b.length + 4 + 4); 208//Message length = message body content length + message ID length 209 BUF. Writeint (B.length + 4); buf. Writeint (messageId); 211 212 if (Protobufmodel! = null) 213 buf. Writebytes (b); 214 return BUF. GetBytes (); 215}216 217 void OnDestroy () 218 {219//after stopping, if you do not close the socket multi-threading and run again, unity will get stuck at the same time Clo Se (); 221}222 223//<summary>224//close socket, terminate thread 225//</summary>226 public void Clo       SE () 227 {228 if (msocket! = null) 229  {230//Microsoft recommends shutdown before closing the socket, but after testing, shutdown will not be able to execute 231 if (msocket.connected) 232 If the network is disconnected         Msocket.shutdown (Socketshutdown.both); 233 msocket.close (); 234 msocket = null;235 }236//Close thread 237 if (threadsend! = null) 238 threadsend.abort (); 239 if (threadreciv E! = null) threadrecive.abort (); 241 Threadsend = null;242 threadrecive = null;243}244 }

Here, the sending and receiving of messages using the socket is basically over, but some projects may increase the functionality of the wire break to enhance the experience, which will be discussed in the next article

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.