相信大家對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>("/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<int>();
// var b = param["b"].ToObject<int>();
// 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客戶端與服務端的對應關系:
當兩個客戶端跟同一個個路徑建立連接的時候,session.IDs 中會產生與之對於應的 唯一 id,用戶可以通過該id對 單個客戶端進行傳值。