This is the 18th day of my participation in Gwen Challenge

The introduction

Sorry everyone, the company has been busy with the project recently, so I have been picking up the articles for a long time now.

Personally, I would like to make a summary of the knowledge I have learned in the process of work, the way to solve problems and the general way to deal with them, so as to facilitate myself and illuminate others. Why is it in the process of work, because only the problems encountered in the real scene are valuable content, I am willing to share, but I can not stay up late to liver articles like some big guys, in line with the principle that the body is the first, appropriate to do some summary is my way of thinking now.

Project description

This time to talk about is not what complex project, is a communication service based on WebSocket procedures.

Before this project, I actually had no contact with communication service program. Before that, I mainly wrote WebApi and background management system interface. , of course, I also know that Tcp is a connection-oriented, reliable, Udp is unreliable these based on knowledge, but in the actual application scenarios using this is the first time, there may be some people think that this kind of simple things have nothing to say, that you can choose to shut down web page, the right thing should be to the right person, and this is my point of view.

Development language c#, the development of a communication program based on WebSocket, the client in accordance with the specified message format to send, the server can be normal parsing.

The message format is as follows

The name of the The frame header The length of the data CRC check Data segment
Length (bytes) 2 2 2 N
instructions TT

All data frames are in high – byte – in – front mode, that is, small – endian mode. The CRC check ranges from the packet head to the packet tail. At the beginning of the check, the CRC check position is cleared first. CRC check mode: The initial check value is 0xAA, and all bytes are summed up in sequence

Project technical preview

How to develop a stable Tcp communication service without precedent?

Before the development of this task, I did not have any experience in communication services. In order to reduce the cost and smooth the development, I chose to use the ready-made framework. After synthesis, I chose RRMQSocket.

The sun and the moon, if out of it; The stars are brilliant, if out of its.

RRQMSocket is an integrated and lightweight network communication service framework. It has the characteristics of high concurrent connection, high concurrent processing, event subscription, plug-in expansion, multi-thread processing, memory pool, object pool and so on, so that users can build the network framework more simply and quickly.

The reasons for choosing him are simple: open source [Gitee recommended project], documented, and ongoing maintenance.

Through the documents provided by the author, I first have a basic understanding of communication services, and then use the framework to write a basic case: a simple TCP communication service, to increase my understanding of the framework.

At this point, work on the frame temporarily high paragraph.

What is the small-endian mode

Generally speaking, the byte order in the computer is divided into two types: big-endian and little-endian a) little-endian the highest byte is first and the lowest byte is second. B) Big-endian byte is in the first place, and high-order byte is in the second place.

Network Endian: The TCP/IP protocols define the byte order as big-endian, so the byte order used in TCP/IP is often called network Endian. A small example: the integer 127 (decimal) in computer (64-bit) large/small endian order

Processing of byte order in c#

First, the default C# uses little endian. Go straight to the case, you can follow the above analysis.

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { byte[] b = { 1, 2, 3, 4 }; Console.WriteLine(bytes2string(b)); Int x1= BitConverter.ToInt32(b, 0); Console.WriteLine(x1.ToString("X2")); / / the x2 is big end model value: x2 = 16909060 = 0 x 01, 02, 03, 04 int x2 = IPAddress.Net workToHostOrder (x1); Console.WriteLine(x2.ToString("X2")); }}}Copy the code

How to convert big endian to little endian?

In the above case a careful server must have figured out how to deal with it

Recommend ways

System.Net.IPAddress.HostToNetworkOrder (conversion) native to the network System.Net.IPAddress.NetworkToHostOrder (network byte into the machine)Copy the code

The other way

The byte array reverse is reversed, that is, the reverse byte order is obtained

byte[].Reverse().ToArray();
Copy the code

Code sample

Short is a short integer. Short 6 is 2 bytes and the memory representation is 06. 00 =06

Use HostToNetworkOrder to convert X to big-endian representation, b=1536, memory representation 00 06

Most calls to ‘BitConverter.GetBytes’ convert the number of big endian bytes 1536 to the big endian array representation 00 06

short x = 6; byte[] aa = System.BitConverter.GetBytes(x); // The default littleendian byte array. short b = System.Net.IPAddress.HostToNetworkOrder(x); / / the x into a corresponding number of big endian byte [] bb = System. BitConverter. GetBytes (b); // This is a big endian byte array.Copy the code

For string type: using System. Text. Encoding. The Default. The GetBytes ();

Take the array of bytes directly from the string.

What is CRC check

CRC is defined

The CRC is the most common error check code in the data communication field. The information field and the length of the check field can be arbitrarily selected. Cyclic redundancy check (CRC) is a data transmission error detection function that performs polynomial calculations on the data and appends the resulting result to the frame. The receiving device performs similar algorithms to ensure correctness and integrity of the data transmission.

CRC check function

Error codes sometimes occur during the transmission of information.

For example, if 1001 is sent and 1000 is received, an error code is generated, but the receiver is not aware of the error code.

When the sender and receiver use the same standard CRC check, they can determine whether error codes occur in the process of information transmission.

Base processing is relevant

C# has some common methods for base processing, record down to facilitate their own later review

A single hexadecimal string is converted to a hexadecimal string
X.tostring ("X2") is converted to uppercase hexadecimal. X.tostring ("x2") is converted to lowercase hexadecimal. 0x0A console. WriteLine(10.toString ("X")); // output A console. WriteLine(10.toString ("X2")); / / 0 aCopy the code

I took the opportunity to revisit the string.Format function again

Console.WriteLine(string.Format("{0:X}", 12)); Format("{0:X2}", 12)); / / output OACopy the code
A byte array to a string is essentially a loop
public static string BytesTostring(byte[] bytes) { string hexString = string.Empty; if (bytes ! = null) { StringBuilder strB = new StringBuilder(); for (int i = 0; i < bytes.Length; i++) { strB.Append(bytes[i].ToString("X2")); } hexString = strB.ToString(); } return hexString; }Copy the code
The official library comes with a byte-handling help class

using namespace System

Method BitConverter.

reference

C# big endian and small endian

String. Format in C#