Use C# to implement websocket server and client communication

1. Introduction to
websocket websocket is a protocol for full-duplex communication over a single TCP connection.

Websocket makes data exchange between client and server easier, allowing the server to actively push data to the client. In the WebSocket API, the browser and the server only need to complete one handshake, and a persistent connection can be created directly between the two, and two-way data transmission can be performed.

2. Background
In order to implement push technology, many websites use polling technology.

Polling is a specific time interval, the browser sends an HTTP request to the client, and then the server returns the latest data to the client's browser. This traditional mode brings obvious disadvantages, that is, the browser needs to make requests to the server continuously, and then the HTTP request may contain a long header, in which the really valid data may be only a small part, which obviously will be wasted. A lot of broadband and other resources.

In this case, HTML5 defines the websocket protocol, which can better save server resources and bandwidth, and enable more real-time communication.

3. Advantages
1. Control overhead

After the connection is established, the packet headers used for protocol control are relatively small when data is exchanged between the server and the client.

2. Stronger real-time performance

Since the protocol is full-duplex, the server can actively send data to the client at any time. Compared with HTTP requests, which need to wait for the client to initiate the request, the server can respond, and the delay is significantly less.

3. Stay connected

Unlike HTTP, Websocket needs to create a connection first, which makes it a stateful protocol, and then some state information can be omitted when communicating. And HTTP requests may need to carry state information (such as authentication, etc.) in each request.

4. Better binary support

5. Support expansion and better compression effect

Fourth, the principle
Websocket is also an application layer protocol like HTTP, but it is a two-way communication protocol built on top of TCP.

Connection process (handshake process)

1. The client and server establish a TCP connection and three-way handshake.

This is the basis of communication, the transmission control layer, if it fails, it will not be executed.

2. After the TCP connection is successful, the client sends the version number information supported by the websocket to the server through the HTTP protocol. (HTTP handshake before starting)

3. After the server receives the handshake request from the client, it also uses the HTTP protocol to return data.

4. After receiving the successful connection message, transmit communication through the TCP channel.

5. The relationship between websocket and socket
Socket is not actually a protocol, but a layer abstracted for the convenience of using TCP and UDP. It is a set of interfaces between the application layer and the transmission control layer.

Socket is the middleware abstraction layer for communication between the application layer and the TCP/IP protocol. It is a set of interfaces. In the design mode, socket is actually a facade mode, which hides the complex TCP/IP protocol behind the socket interface. For the user, a set of simple interfaces is all, let the socket organize the data to conform to the specified protocol. .

The communication between the two hosts must be connected through a socket, and the socket uses the TCP/IP protocol to establish a TCP connection. The TCP connection is more dependent on the underlying IP protocol, and the IP protocol connection is dependent on lower layers such as the link layer.

Websocket is a typical application layer protocol.

6. Use C# to realize the communication between the websocket server and the client
(1) SuperWebSocket realizes the server
1. Create a window program, WindowsFormsWebsocketServer

2. Add the package

Tools-->Nuget Package Management-->Manage Nuget Packages of Solutions-->Search for SuperWebSocket, select SuperWebSocketNETServer, click Install on the right, wait for the installation to complete, after the installation is complete, there will be many more reference libraries in the project, as follows 

3. Code example

using SuperWebSocket;
using System;
using System.Windows.Forms;
 
namespace WindowsFormsWebsocketServer
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            websocketServer();
        }
 
        private void websocketServer()
        {
            Log("我是服务端");
            WebSocketServer webSocketServer = new WebSocketServer();
            webSocketServer.NewSessionConnected += WebSocketServer_NewSessionConnected;
            webSocketServer.NewMessageReceived += WebSocketServer_NewMessageReceived;
            webSocketServer.SessionClosed += WebSocketServer_SessionClosed;
            if (!webSocketServer.Setup("127.0.0.1", 1234))
            {
                Log("设置服务监听失败!");
            }
            if (!webSocketServer.Start())
            {
                Log("启动服务监听失败!");
            }
            Log("启动服务监听成功!");
            //webSocketServer.Dispose();
        }
 
        private void WebSocketServer_NewSessionConnected(WebSocketSession session)
        {
            Log("欢迎客户端: 加入");
            //SendToAll(session, msg);
        }
 
        private void WebSocketServer_NewMessageReceived(WebSocketSession session, string value)
        {
            Log("服务端收到客户端的数据 ==》"+value);
            //SendToAll(session, value);
        }
 
        private void WebSocketServer_SessionClosed(WebSocketSession session, SuperSocket.SocketBase.CloseReason value)
        {
            Log("客户端:关闭,原因:");
            //SendToAll(session, msg);
        }
 
        /// <summary>
        /// 广播,同步推送消息给所有的客户端
        /// </summary>
        /// <param name="webSocketSession"></param>
        /// <param name="msg"></param>
        public static void SendToAll(WebSocketSession webSocketSession, string msg)
        {
            foreach (var item in webSocketSession.AppServer.GetAllSessions())
            {
                item.Send(msg);
            }
        }
 
        private delegate void DoLog(string msg);
        public void Log(string msg)
        {
            if (this.logReveal.InvokeRequired)
            {
                DoLog doLog = new DoLog(Log);
                this.logReveal.Invoke(doLog, new object[] { msg });
            }
            else
            {
                if (this.logReveal.Items.Count > 20)
                {
                    this.logReveal.Items.RemoveAt(0);
                }
                msg = DateTime.Now.ToLocalTime().ToString() + " " + msg;
                this.logReveal.Items.Add(msg);
            }
        }
    }
}

2) WebSocket4Net realizes the client
1. Create a window program, WindowsFormsWebsocketClient

2. Add the package

Tools-->Nuget Package Management-->Manage Nuget Packages for Solutions-->Search for WebSocket4Net, select WebSocket4Net, click Install on the right, wait for the installation to complete, after the installation is complete, there will be many more reference libraries in the project, as follows 

3. Code example

using System;
using WebSocket4Net;
using System.Threading;
using System.Windows.Forms;
 
namespace WindowsFormsWebsocketClient
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            websocketServerTest();
        }
 
        public static WebSocket webSocket4Net = null;
        public void websocketServerTest()
        {
            FileUtil.getInstance().Log("我是客户端");
            webSocket4Net = new WebSocket("ws://127.0.0.1:1234");
            webSocket4Net.Opened += WebSocket4Net_Opened;
            webSocket4Net.Error += websocket_Error;
            webSocket4Net.Closed += new EventHandler(websocket_Closed);
            webSocket4Net.MessageReceived += WebSocket4Net_MessageReceived;
            webSocket4Net.Open();
            Thread thread = new Thread(ClientSendMsgToServer);
            thread.IsBackground = true;
            thread.Start();
            //webSocket4Net.Dispose();
        }
 
        private void saveBtn_Click(object sender, EventArgs e)
        {
            websocketServerTest();
        }
 
        public void ClientSendMsgToServer()
        {
            int i = 1;
            while (true)
            {
                webSocket4Net.Send("love girl" + i++);
                Thread.Sleep(TimeSpan.FromSeconds(5));
            }
        }
 
        private void WebSocket4Net_MessageReceived(object sender, MessageReceivedEventArgs e)
        {
            FileUtil.getInstance().Log("服务端回复的数据:" + e.Message);
        }
 
        private void WebSocket4Net_Opened(object sender, EventArgs e)
        {
            FileUtil.getInstance().Log("客户端连接成功!发送数据中...");
            webSocket4Net.Send("来自客户端,准备发送数据!");
        }
 
        private void websocket_Error(object sender, EventArgs e)
        {
            FileUtil.getInstance().Log("WebSocket错误");
            Thread.Sleep(5000);
            if (webSocket4Net.State!= WebSocketState.Open&&webSocket4Net.State!=WebSocketState.Connecting)
            {
                websocketServerTest();
            }
        }
 
        private void websocket_Closed(object sender, EventArgs e)
        {
            FileUtil.getInstance().Log("WebSocket已关闭");
            Thread.Sleep(5000);
            if (webSocket4Net.State != WebSocketState.Open && webSocket4Net.State != WebSocketState.Connecting)
            {
                websocketServerTest();
            }
        }
    }
}

(3) The client sends a message to the server

Client:

Server:

 

{{o.name}}
{{m.name}}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324138323&siteId=291194637