WPF--Implementing WebSocket server

1. What is websocket?
WebSocket is a new protocol under HTML5 (the websocket protocol is essentially a tcp-based protocol).
It realizes full-duplex communication between the browser and the server, which can better save server resources and bandwidth and achieve real-time The purpose of communication
Websocket is a persistent protocol
. 2. The principle of websocket. Websocket
agrees on a communication specification. Through a handshake mechanism, a TCP-like connection can be established between the client and the server to facilitate communication between them.
Before the emergence of websocket, web interactions were generally short connections or long connections based on the http protocol.
Websocket is a brand new protocol that does not belong to the http stateless protocol. The protocol is called "ws"
. The relationship between websocket and http
 is the same:

Both are based on TCP, both are reliable transmission protocols,
and both are application layer protocols
. The differences are:

WebSocket is a two-way communication protocol that simulates the Socket protocol and can send or receive information in both directions.
HTTP is one-way.
WebSocket requires the browser and server to shake hands to establish a connection.
HTTP is when the browser initiates a connection to the server. The server does not know this in advance. Contact
 :

When WebSocket establishes a handshake, data is transmitted via HTTP. But after it is established, the HTTP protocol is not needed during actual transmission.
Summary (overall process):

First, the client initiates an http request, and after three handshakes, a TCP connection is established; the http request stores information such as the version number supported by WebSocket, such as: Upgrade, Connection, WebSocket-Version, etc.; then, the server receives the client's
handshake After the request, the HTTP protocol is also used to feedback data;
finally, after the client receives the message of successful connection, it starts full-duplex communication with the help of the TCP transmission channel. 

1. XAML code

<Window x:Class="Freed.WebSocket.Service.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Freed.WebSocket.Service"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <TextBox x:Name="textBox_Address" HorizontalAlignment="Left" Height="23" Margin="25,20,0,0" TextWrapping="Wrap"  VerticalAlignment="Top" Width="493"/>
        <Button x:Name="button" Content="启动" HorizontalAlignment="Left" Margin="552,23,0,0" VerticalAlignment="Top" Width="75" Click="button_Click"/>
        <TextBox x:Name="textBox_Content" HorizontalAlignment="Left" Height="294" Margin="31,72,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="672"/>
        <Button x:Name="but_Send" Content="发送" HorizontalAlignment="Left" Margin="633,23,0,0" VerticalAlignment="Top" Width="75" Click="but_Send_Click"/>

    </Grid>
</Window>

2. Backend code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WebSocketSharp.Server;

namespace Freed.WebSocket.Service
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void button_Click(object sender, RoutedEventArgs e)
        {
            StartWebSocket(this.textBox_Address.Text);
        }


        WebSocketServer wssv;
        void StartWebSocket(string Ip)
        {
            wssv = new WebSocketServer(IPAddress.Parse(this.textBox_Address.Text), 9999);
            wssv.AddWebSocketService<ServerSharp>("/Server");
            wssv.Start();
            if (wssv.IsListening)
            {
                MessageBox.Show(string.Format("Listening on port {0}, and providing WebSocket services:", wssv.Port));
                foreach (var path in wssv.WebSocketServices.Paths)
                    MessageBox.Show(string.Format("- {0}", path));
            }

        }

        //发送
        private void but_Send_Click(object sender, RoutedEventArgs e)
        {
            wssv.WebSocketServices.Broadcast(this.textBox_Content.Text);
        }
    }
}

2.1  ServerSharp

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using WebSocketSharp;
using WebSocketSharp.Server;

namespace Freed.WebSocket.Service
{
    public class ServerSharp : WebSocketBehavior
    {
        int count = 0;
        protected override void OnClose(CloseEventArgs e)
        {
            count++;
            Task tk = new Task(() => {
                MessageBox.Show("客户端关闭连接");

            });
            tk.Start();
        }

        protected override void OnError(ErrorEventArgs e)
        {
            Task tk = new Task(() => {
                MessageBox.Show($"客户端连接异常:{e.Message}");
            });
            tk.Start();
        }

        protected override void OnMessage(MessageEventArgs e)
        {
            Task tk = new Task(() => {
                Send("接收到消息:" + e.Data);
            });
            tk.Start();
        }
    }
}

Guess you like

Origin blog.csdn.net/beautifull001/article/details/126017181