C# 完成WebSocket 服务


相信大家对WebSocket 有所了解,这里就不对WebSocket 进行介绍了 ,直接上菜!

.net core 或  .net 5.0 ,本人用的是 .net 5.0的开发环境,引用下面两个包

 本人新建的是窗体控件,窗体代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WebSocketSharp.Server;

namespace websocket09
{
public partial class Form1 : Form
{
private WebSocketServer wssv;
public Form1()
{
InitializeComponent();
wssv = new WebSocketServer(6690);
}

private void button1_Click(object sender, EventArgs e)
{
wssv.AddWebSocketService("/add");
if (wssv.IsListening == true)
{
showMassage("服务已经成功,无需再次启动!");
return;
}
wssv.Start();
showMassage("服务启动成功!");
}

private void button2_Click(object sender, EventArgs e)
{
if (wssv.IsListening == false)
{
showMassage("服务已经关闭,不能发送消息!");
return;
}
var tt = wssv.WebSocketServices.Hosts.ToList();
tt[0].Sessions.SendTo(this.textBox2.Text, tt[0].Sessions.IDs.ToList()[0]);
}

private void button3_Click(object sender, EventArgs e)
{
if (wssv.IsListening == false)
{
showMassage("服务已经关闭,无需再次关闭!");
return;
}
wssv.Stop();
showMassage("服务已经关闭!");
}
//展示获取的消息
public void showMassage(string showstr) {
this.textBox1.Text = this.textBox1.Text + "\r\n" +"获取客户端消息! " +showstr;
}
}
}

以及新建一个类  add 对应的是,websocket的路径,

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

namespace websocket09
{
class Add : WebSocketBehavior
{
protected override void OnOpen()
{
Console.WriteLine("Connection Open");
base.OnOpen();
}
protected override void OnMessage(MessageEventArgs e)
{
var data = e.Data;
//if (TestJson(data))
//{
// var param = JToken.Parse(data);
// if (param["a"] != null && param["b"] != null)
// {
// var a = param["a"].ToObject();
// var b = param["b"].ToObject();
// Send(JsonConvert.SerializeObject(new { code = 200, msg = "result is " + (a + b) }));
// Task.Factory.StartNew(() => {
// Task.Delay(10000).Wait();
// Send(JsonConvert.SerializeObject(new { code = 200, msg = "I just to tell you, the connection is different from http, i still alive and could send message to you." }));
// });
// }
//}
//else
//{
// Send(JsonConvert.SerializeObject(new { code = 400, msg = "request is not a json string." }));
//}
}

protected override void OnClose(CloseEventArgs e)
{
Console.WriteLine("Connection Closed");
base.OnClose(e);
}

protected override void OnError(ErrorEventArgs e)
{
//Console.WriteLine("Error: " + e.Message);
base.OnError(e);
}

private static bool TestJson(string json)
{
try
{
JToken.Parse(json);
return true;
}
catch (JsonReaderException ex)
{
Console.WriteLine(ex);
return false;
}
}
}
}

 通过上面代码添加对应的路径信息,然后书写webscket前端对应的代码,如下:


         
         
                  //检查浏览器是否支持WebSocket         if (!window.WebSocket) {             console.log('您的浏览器不支持WebSocket,请选择其他的浏览器再尝试连接服务器');         }         var el = document.getElementById("textarea");         var wsClient = new WebSocket('ws://999.999.888.333:6690/add');                 wsClient.open = function (e) {             el.value += "连接成功!\r\n";         }         wsClient.onclose = function (e) {             el.value += "连接断开!\r\n";         }         wsClient.onmessage = function (e) {             console.log(wsClient);             el.value += "接收消息:" + e.data + "\r\n";         }         wsClient.onerror = function (e) {             el.value += "连接失败!原因【" + e.data + "】\r\n";         }         function send() {             var oText = document.getElementById("message");             wsClient.send(oText.value);         }     

 展示效果如图下:

后端:

客户端;

重点 重点 重点 需要了解websocket客户端与服务端的对应关系:

 当两个客户端跟同一个个路径建立连接的时候,session.IDs 中会产生与之对于应的 唯一 id,用户可以通过该id对 单个客户端进行传值。