当前位置:网站首页>WPF -- implement websocket server
WPF -- implement websocket server
2022-07-28 20:07:00 【Persistent Tao】
One , What is? websocket
WebSocket yes HTML5 Next new protocol (websocket A protocol is essentially a foundation tcp The agreement )
It realizes full duplex communication between browser and server , Can better save server resources and bandwidth and achieve the purpose of real-time communication
Websocket It's a persistent protocol
Two ,websocket Principle
websocket Agreed on a communication specification , Through a handshake mechanism , A similar connection can be established between the client and the server tcp The connection of , So as to facilitate the communication between them
stay websocket Before appearance ,web Interaction is generally based on http Short connection or long connection of protocol
websocket It's a new kind of agreement , Do not belong to http Stateless protocol , The agreement is called "ws"
3、 ... and ,websocket And http The relationship between
The same thing :
It's all based on tcp Of , They're all reliable transport protocols
These are application layer protocols
Difference :
WebSocket It's a two-way communication protocol , simulation Socket agreement , Can send or receive messages in both directions
HTTP Is one-way
WebSocket It requires the browser and server to handshake to establish a connection
and http It's the browser that initiates the connection to the server , The server does not know the connection in advance
contact :
WebSocket When establishing a handshake , The data is through HTTP Transmission of . But after it was built , It's not necessary to HTTP Agreed
summary ( The overall process ):
First , Client initiated http request , after 3 After a handshake , Set up TCP Connect ;http Put... In the request WebSocket Supported version number and other information , Such as :Upgrade、Connection、WebSocket-Version etc. ;
then , After the server receives the client's handshake request , Same use HTTP Protocol feedback data ;
Last , After the client receives the message of successful connection , Start with TCP Transmission channel for full duplex communication .
One 、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=" start-up " 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=" send out " HorizontalAlignment="Left" Margin="633,23,0,0" VerticalAlignment="Top" Width="75" Click="but_Send_Click"/>
</Grid>
</Window>Two 、 Background 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 Interaction logic of
/// </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));
}
}
// send out
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(" The client closes the connection ");
});
tk.Start();
}
protected override void OnError(ErrorEventArgs e)
{
Task tk = new Task(() => {
MessageBox.Show($" Client connection exception :{e.Message}");
});
tk.Start();
}
protected override void OnMessage(MessageEventArgs e)
{
Task tk = new Task(() => {
Send(" Message received :" + e.Data);
});
tk.Start();
}
}
}
边栏推荐
- Getting started with enterprise distributed crawler framework
- [network] cross area network communication learning classification and calculation of IPv4 address
- Leetcode Day5 delete duplicate email
- Cloud computing notes part.1 - system management
- mmo及时战斗游戏中的场景线程分配
- leetcode day1 分数排名
- Find the memory occupied by the structure
- C language pointer and two-dimensional array
- 7. Functions of C language, function definitions and the order of function calls, how to declare functions, prime examples, formal parameters and arguments, and how to write a function well
- Cdga | how can the industrial Internet industry do a good job in data governance?
猜你喜欢

Question bank and answers of the latest national fire-fighting facility operators (intermediate fire-fighting facility operators) in 2022

Idea properties file display \u solution of not displaying Chinese
![[C language] string reverse order implementation (recursion and iteration)](/img/c3/02d0a72f6026df8a67669293e55ef2.png)
[C language] string reverse order implementation (recursion and iteration)
![[C language] header file of complex number four operations and complex number operations](/img/f9/b389fe5367f1fa6cd18aaac856bc0d.png)
[C language] header file of complex number four operations and complex number operations

JS preventdefault() keyboard input limit onmousewheel stoppropagation stop event propagation

Codeignier framework implements restful API interface programming
![[C language] simulation implementation of pow function (recursion)](/img/7b/ef8b3d97adc7810de249a37642c71f.png)
[C language] simulation implementation of pow function (recursion)

Basic usage of docker
![[C language] Gobang game [array and function]](/img/73/1e708b0640c2dbc86393206840b059.png)
[C language] Gobang game [array and function]

Source insight project import and use tutorial
随机推荐
A chip company fell in round B
Stories of Party members | Li qingai uses cartoons to drive farmers to increase income and become rich
软考高级考试中有五大证书,哪个更值得考?
跨区域网络的通信学习静态路由
Leetcode day3 employees who exceed the manager's income
English translation Portuguese - batch English conversion Portuguese - free translation and conversion of various languages
Servlet学习笔记
KubeEdge发布云原生边缘计算威胁模型及安全防护技术白皮书
Implementation of memmove in C language
Leetcode Day1 score ranking
Kubeedge releases white paper on cloud native edge computing threat model and security protection technology
Use Hal Library of STM32 to drive 1.54 inch TFT screen (240*240 st7789v)
[C language] string reverse order implementation (recursion and iteration)
Circular linked list OJ question
Array method added in ES6
There is a 'single quotation mark' problem in the string when Oracle inserts data
Know small and medium LAN WLAN
Andorid system layout, values, drawable adaptation
Integration and implementation of login click graphic verification code in personal blog system
党员故事|李青艾用漫画带动农民增收致富