C # socket TCP protocol Receiver

Source: Internet
Author: User

This Protocol receiver can receive a single Protocol up to 10 MB. A single instance of this Protocol receiver can stably receive protocol data of kb/s. The cumulative running time exceeds 20000 hours.

 

Main call method after instantiation

Receiveactive

After receiving a dozen complete protocols

Onprotocolreceived event

Protocol deserialization, for CLR objects in

 protected virtual void ProtocolReceivedByThreadPool(byte[] byteProtocolData)

Method

 

Method needs to be instantiated

 

/// <Summary> /// DECT protocol receiver /// </Summary> public class dectprotocolreceiver {# visible attributes of the region subclass # endregion # region constructor /// <summary> /// create a new Protocol Parser image /// </Summary> Public dectprotocolreceiver () {}# endregion # method visible to the region subclass /// <summary> /// search for the location where pattern appears in the byte array of data /// C # byte [] Search/ // simple functions, search for the location where pattern appears in the byte array of data. Of course, this function can be expanded here, for example, to ignore case sensitivity and prevent exceptions. /// </Summary> /// <Param name = "data"> byte array search for data </param> /// <Param name = "pattern"> Search for Pattern </param> /// <returns> the returned result is a list Int, if the size is 0, the search fails. </Returns> protected virtual list <int> indexof (byte [] data, byte [] pattern) {// list int Temporary Variable list <int> matchedpos = new list <int> (); // check whether the current data can be searched if (data. length = 0 | data. length <pattern. length) {return matchedpos;} // calculates the end length of the search. Int end = data. length-pattern. length; // whether bool matched = false is found; // start searching for (INT I = 0; I <= end; I ++) {// single-byte search for (Int J = 0; j <pattern. length |! (Matched = (j = pattern. Length); j ++) {If (data [I + J]! = Pattern [J]) break;} If (matched) {matched = false; matchedpos. add (I) ;}return matchedpos ;}# if Silverlight gb2312.gb2312encoding gb2312 = new gb2312.gb2312encoding (); # endif // <summary> // method used for receiving in the thread pool // process protocol data, including deserialization and other functions // The Event Notification has received the Protocol // /</Summary> // <Param name = "byteprotocoldata"> protocol data buffer </param> protected virtual void protocolreceivedbythreadpool (byte [] byteprotocoldata) {// temporary String string mathe = asciiencoding. ASCII. getstring (byteprotocoldata, 0, byteprotocoldata. length);/* here is the serialization method of the decoding Protocol */registonprotocolinclued (mathe );} # endregion # region variable definition // <summary> // byte cache // use the foreach performance test to add a private queue for 5242880 times in 78.123 milliseconds. // </Summary> private queue <byte> bytecache = new queue <byte> (); /// <summary> /// string used for splitting the Protocol or byte [] /// </Summary> private byte [] splicspace = asciiencoding. ASCII. getbytes ("\ r \ n"); // <summary> // defines a thread pool callback function // </Summary> private system. threading. waitcallback threadpoolfun = NULL; # endregion # region iprotocolreceiver member // <summary> // receives data actions /// </Summary> /// <Param name = "bytearray"> received data </param> Public Virtual void receiveactive (byte [] bytearray) {# region decompress receiveactivedcompress (bytearray); # endregion} // <summary> // receives data with the decompression action /// </Summary> // <Param name = "bytearray"> received data </param> Public Virtual void receiveactivedcompress (byte [] bytearray) {If (bytearray. length> 0) {// if data is cleared more than 10 MB, // This is used to send a large number of error data to the server for post-processing if (bytecache. count> 1024*1024*10) {// clear data to ensure that the memory does not rise bytecache. clear ();} // if the data is not initialized if (bytearray. length! = 1 & bytearray! = New byte [1]) {# add region to the cache queue // Add the object to the end of system. Collections. Generic. Queue <t>. Foreach (byte B in bytearray) {// Add the object to the end of system. Collections. Generic. Queue <t>. Bytecache. enqueue (B) ;}# endregion // list of locations where the search delimiter appears <int> ints = indexof (bytecache. toarray (), splicspace ); # region splits and decrypts the decrypted image data and saves the decrypted data to the list of useful data sets for the image // current <byte []> currentbytearraycollection = new list <byte []> (); // Save the current object to the set for (INT Index = 0; index <ints. count; index ++) {# region retrieve the expected data // get the data to be skipped int skip = 0; // (Index = 0? 0: Index); // obtain the data to be retrieved. // if this is the first data in ints, the second occurrence and the subsequent data will be // The current position minus the previous position minus the expected splitting String Length int take = (Index = 0? Ints [Index]: ints [Index]-ints [index-1]-splicspace. length); // meaning Data byte [] protocoldata = bytecache. skip (skip ). take (take ). toarray (); # endregion // Add to the data cache set currentbytearraycollection. add (protocoldata); # region removes the data from the cache queue // start to extract the data and decrypt the data in foreach (byte bytesingle in protocoldata) {// remove the object like bytecache. dequeue ();} // remove the separator foreach (byte splictbyte in splicspace) {// remove the object like bytecache. dequeue () ;}# end Region} # endregion foreach (byte [] byteprotocoldata in currentbytearraycollection) {// Add the thread program call method to the 2010-11-25 # // define the callback method of the thread pool if (threadpoolfun = NULL) {threadpoolfun = new system. threading. waitcallback (o) =>{// use the method to forward data, and the receiver processes protocolreceivedbythreadpool (byte []) O );});} // Add the method to the thread pool queue to improve efficiency system. threading. threadpool. queueuserworkitem (threadpoolfun, byteprotocoldata);} currentbytearraycolle Ction = NULL; ints = NULL ;}}} # endregion # region iprotocolreceiver member // <summary> // register the event /// </Summary> /// <Param name = "_ Param"> parameter </Param> protected void registonprotocolreceived (string _ PARAM) {If (onprotocolreceived! = NULL) {onprotocolreceived (this, new routedpropertychangedeventargs <string> (null, _ PARAM ));}} /// <summary> /// when a packet of data is parsed /// </Summary> public event routedpropertychangedeventhandler <string> onprotocolreceived; /// <summary> /// the exception occurred when deserializing the image // </Summary> public event routedpropertychangedeventhandler <byte []> deserializeexceptioned; # endregion # region iprotocolreceiver member // <summary> // clear the cache information /// </Summary> Public void cacheclear () {bytecache. clear () ;}# endregion}

 

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.