https://www.cnblogs.com/dathlin/p/12303098.html
在Visual Studio 中的NuGet管理器中可以下载安装,也可以直接在NuGet控制台输入下面的指令安装:
Install-Package HslCommunication
#服务端
private WebSocketServer wsServer;
private void button1_Click( object sender, EventArgs e )
{
try
{
wsServer = new WebSocketServer( );
wsServer.OnClientApplicationMessageReceive += WebSocket_OnClientApplicationMessageReceive;
wsServer.ServerStart( 1883 );
MessageBox.Show( "Start Success" );
}
catch (Exception ex)
{
MessageBox.Show( "Start Failed : " + ex.Message );
}
}
private void WebSocket_OnClientApplicationMessageReceive( WebSocketSession session, WebSocketMessage message )
{
Invoke( new Action( ( ) =>
{
if(!isStop)
textBox8.AppendText( $"OpCode:[{message.OpCode}] Mask:[{message.HasMask}] Payload:[{Encoding.UTF8.GetString( message.Payload )}]" + Environment.NewLine );
} ) );
}
}
#客服端
<
script
type="text/javascript">
function WebSocketTest()
{
if ("WebSocket" in window)
{
// 打开一个 web socket
var ws = new WebSocket("ws://127.0.0.1:1883");
ws.onopen = function()
{
console.log("已经打开...");
};
ws.onmessage = function (evt)
{
var received_msg = evt.data;
console.log(received_msg);
};
}
else
{
console.log("您的浏览器不支持 WebSocket!");
}
}
</
script
>