C# Websocket connection (wss)

1, What is Websocket?

1.WebSocket is a new protocol under HTML5 (websocket protocol is essentially a tcp based protocol)
2. It realizes full duplex communication between browser and server, which can better save server resources and bandwidth and achieve the purpose of real-time communication
3.Websocket is a persistent protocol

2, What is the difference between Websocket, Socket, Http and Mqtt?

Socket:
Socket is the encapsulated interface of tcp/ip protocol family. Socket connection can specify different transport layer protocols, namely TCP or UDP. Because it is based on tcp/ip, it is generally used for communication in LAN.

WebSocket:
Websocket protocol is a new network protocol based on TCP. Like http protocol, it belongs to application layer protocol. It is a technology that enables two-way real-time communication (full duplex) between client and server. It supports long connection and can communicate between the Internet. The websocket protocol that ws and wss represent plaintext and ciphertext respectively is introduced, and the default port is 80 or 443, which is almost the same as http. Websocket also needs a handshake process before it can officially send and receive data. Because the header protocol of data packet is small, unlike http, which needs to carry a complete header for each request, the network overhead is relatively small, and the delay of long connection is significantly less (there is no need to repeatedly create a new connection).

MQTT:
MQTT protocol is designed for the communication of a large number of remote sensors and control devices with limited computing power and working in low bandwidth and unreliable networks. It has the following main characteristics:
1. Use publish / subscribe message mode to provide one to many message publishing and decouple applications;
2. Message transmission for shielding load content;
3. Use TCP/IP to provide network connection;

HTTP:
HTTP is an application layer that transfers data (HTML files, picture files, query results, etc.) based on TCP/IP communication protocol.
Communication mode:
1. As an HTTP client, the browser sends a request to the HTTP server, that is, the web server, through the URL. The web server sends response information to the client according to the received request.
2.HTTP Request message: request line, Request header, blank line and Request data.
3.HTTP Response message Response: the HTTP Response is also composed of four parts: status line, message header, blank line and Response body.
If the connection mode is close, the server will actively close the TCP connection, and the client will passively close the connection and release the TCP connection; If the connection mode is keepalive, the connection will be maintained for a period of time, during which you can continue to receive requests;

3, WS and WSS protocols
Both WS protocol and WSS protocol are schems of WebSocket protocol. One is non secure and the other is secure. It is also a unified resource identifier. Just like the difference between HTTP protocol and HTTPS protocol. There is no certificate for non secure, and SSL certificate is required for secure. (SSL is developed by Netscape to ensure the security of data transmission in the network. It mainly uses data encryption technology to avoid data being stolen or monitored in the transmission process.) Where WSS represents WebSocket above TLS. Ws generally defaults to port 80, while WSS defaults to port 443. Most websites use ports 80 and 433. (in the process of advanced anti DDoS protection, websites with ports 80 and 433 need to be recorded before they can be connected to China.) Of course, the website will also have other ports. If this kind of advanced anti DDoS scheme is made, overseas advanced anti DDoS can be used. The embodiment forms of WS and WSS are TCP+WS AS WS and TCP+TLS+WS AS WS respectively. The server URL is the URL. Finally, let's talk about the characteristics of WebSocket protocol: Based on TCP protocol, the server is easy to implement; It has good compatibility with HTTP protocol. It is not easy to be shielded when shaking hands. It can be through various HTTP proxy servers; Lightweight data and real-time communication; Text and binary data can be sent. Without limiting the homology, the client can communicate with any server. Therefore, the emergence of WebSocket protocol has solved the troublesome problems of extension and compatibility protocols for many people.

WSS connection: because WSS is based on SSL, two-way authentication is required. When the client connects to the server, I need to add a certificate (the server can not be added without authentication), and the server verifies. Note: the customer also needs to verify the server, so the server certificate callback needs to be added for verification. This is ignored by many people, so there is a prompt that the remote server cannot be connected and TLS/SSL verification fails.

		public MainWindow()
		{
			InitializeComponent();
			RemoteCertificateValidationCallback remote = ValidateServerCertificate;
			ServicePointManager.ServerCertificateValidationCallback = remote;
		}
		/// <summary>
		///Server verification
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="certificate"></param>
		/// <param name="chain"></param>
		/// <param name="sslPolicyErrors"></param>
		/// <returns></returns>
		public bool ValidateServerCertificate( object sender,X509Certificate certificate,X509Chain chain,SslPolicyErrors sslPolicyErrors)
		{
			return   true ;
		}		
        /// <summary>
		///WebSocket client connection
		/// </summary>
		/// <param name="param"></param>
		/// <returns></returns>
		public async Task Connect()
		{
			CancellationTokenSource t = new CancellationTokenSource();
			try
			{
				client.Options.SetRequestHeader("key", "value");
				X509Certificate2 cert = new X509Certificate2("xxx.cert");
				client.Options.ClientCertificates.Add(cert);
				Uri uri = new Uri("wss://xxxxxx");
				//var config=new ServerConfig
				await client.ConnectAsync(uri, t.Token);
				Thread.Sleep(300);
				Console.WriteLine($"link websocket:[{uri}] complete");
				Task s1 = new Task(Receive, t, t.Token, TaskCreationOptions.LongRunning);
				s1.Start();
				token = t;
				Console.WriteLine("Send Hello");
			}
			catch (Exception ex)
			{
				Console.WriteLine($"link websocket:[{uri}] fail", ex.Message);

			}
		}
		/// <summary>
		///Websocket receive
		/// </summary>
		/// <param name="obj"></param>
		private void Receive(object obj)
		{
			CancellationTokenSource ts = obj as CancellationTokenSource;
			byte[] bs = new byte[1024];
			while (!ts.Token.IsCancellationRequested)
			{
				try
				{
					ArraySegment<byte> buff = new ArraySegment<byte>(bs, 0, bs.Length);
					Task<WebSocketReceiveResult> res = client.ReceiveAsync(buff, ts.Token);
					res.Wait();
					if (ts.Token.IsCancellationRequested)
					{
						return;
					}
					if (WebSocketCloseStatus.NormalClosure == res.Result.CloseStatus)
					{
						Console.WriteLine($"websocket:Disconnect from server:{res.Result.CloseStatus} --> Desc :{res.Result.CloseStatusDescription}");
						ts.Cancel();
						return;
					}
					string strData = encod.GetString(bs, 0, res.Result.Count);
					Console.WriteLine(strData);
					WsMsg msg = WsMsg.Deserialize(strData);
				}
				catch (Exception ex)
				{
					Console.WriteLine("Parse or execute websocket:command failed", ex);
				}
			}
		}

Websocket client and server communication code reference:

WebSocket protocol: 5 minutes from entry to mastery - program ape card - blog Garden

C# WebSocket_ Xiong Siyu's blog - CSDN blog_ c# websocket

C# WebSocket - Southern leaves - blog Park

Tags: C# Network Protocol websocket

Posted by alco19357 on Sat, 21 May 2022 22:14:31 +0300