Tuesday 15 July 2014

c# - is there a better way of sending a list of int over a socket? -


I can have more int (10 to 1000 ints) than TCP

I

I also use the BeginSend / BeginReiveive pattern (a thread for each).

I came up with the simple code that I want

  const int ofInt = sizeof (int); Int index = 0; Var Basic List = New List & lt; Int & gt; (); OriginalList.Add (1); OriginalList.Add (42); // ..... original list.ed (9 001); // wire ArrayOfByte = Create and send ArrayOfByte on new byte [OriginalList.Count * sizeOfInt]; Foreign Language (various items in original) {Array.Copy (Bitakonar.getbaytes (item), 0, Arrayfight, Index, sizeoffient); Index + size = size; } //socket.BeginSend(ArrayOfByte .... //socket.BeginReceive (ArrayOfByte .... //) Move it to a list and lieutenant; int and gt; int length = arrayoffbite.langer; var copyofflist = new List & lt; int & gt; (Letter / SizeFont); (Index = 0; Index Left | Index + = Sizeoffice) {Copy OffList.Add (BitTracker toInt32 (ArrayBoit, Index));}   

Thoughts:

That one is very Examples of collecting unnecessary small byte [] ; This is a Bit BitConverter is a pain API, but it can be avoided; I probably just use bit-OS (change / more) to write bytes, because this allows the CPU -Andendance issues are avoided, but it can also be done with unsafe very efficiently; A BinaryWriter will also work

CPU endianness

You really do not need byte [] for everyone, you can just do the content Write in the note, however, note that if you have socket buffering disabled ( NoDelay etc.) you probably think that is appropriate size for packet> if you have a potential integer If you know more information about, then more efficient representations may be available - for example, "varint" encoding (basically, how UTF-8 encodes less characters in a byte, and for higher characters Use of multi-byte

In order to effectively process data for the consumer, you should also send the number of elements or the payload size of the elements, so the receiver is aware when a logical frame is received - Unless there is only one message on the socket


some example bit-op based socket code:

  int index = 0; Forex Currency (different Values ​​in the list) {buffer [index ++] = (byte) val; Buffer [index ++] = (byte) (Val & gt; & gt; 8); Buffer [index ++] = (byte) (val>> gt; 16); Buffer [index ++] = (byte) (val> & gt; 24); If (index == buffer lang) {// flush buffer socket. Write (buffer, 0, index); Index = 0; }} If (index! = 0) {// final flush socket. Write (buffer, 0, index); }  

The reading code needs to be ensured that there are some integer values ​​before the start, then:

  while (index and lieutenant; Available bets) {int val = buffer [index ++] | (Buffer [index ++] & lt; & lt; 8). (Buffer [index ++] & lt; & lt; 16) | (Buffer [index ++] & lt; 24); List.Add (Val); }  

No comments:

Post a Comment