C#實現(xiàn)websocket雙向通信的示例代碼
更新時間:2024年06月26日 11:13:56 作者:靚仔很忙i
本文基于WebSocketSharp實現(xiàn)了websocket雙向通信,除基本的客戶端向服務端發(fā)送消息外,也支持客戶端向指定的客戶端發(fā)送消息、群發(fā)消息,其他協(xié)議可自定義,廢話不多說,直接上干貨,需要的朋友可以參考下
一.服務端
新建一個.net項目,如websocket.server
安裝包
Install-Package WebSocketSharp -Pre
定義WebSocketHelper
using CaseAuto.helper.websocket; using System.Collections.Generic; using WebSocketSharp.Server; namespace CaseAuto.helper { public class WebSocketHelper { static WebSocketServer wssv = new WebSocketServer("ws://127.0.0.1"); private static Dictionary<string,CaseInfoBehavior> clients = new Dictionary<string,CaseInfoBehavior>(); public static void Init() { wssv.AddWebSocketService<CaseInfoBehavior>("/caseInfo",()=>new CaseInfoBehavior(clients)); wssv.Start(); } public static void End() { wssv.Stop(); } } }
創(chuàng)建CaseInfoBehavior
using Newtonsoft.Json; using System; using System.Collections.Generic; using WebSocketSharp; using WebSocketSharp.Server; namespace CaseAuto.helper.websocket { public class CaseInfoBehavior : WebSocketBehavior { private string _username; private Dictionary<string, CaseInfoBehavior> _clients = new Dictionary<string, CaseInfoBehavior>(); public CaseInfoBehavior(Dictionary<string,CaseInfoBehavior> clients) { _clients = clients; } protected override void OnMessage(MessageEventArgs e) { var data=JsonConvert.DeserializeObject<WebSocketMsgModel>(e.Data); switch (data.msgType){ case MsgType.NORMAL: var msg = $"This msg from serve,I recive msg:{data.content}"; Send(msg); break; case MsgType.GROUP: SendMessageToAll(data.content); //Sessions.Broadcast(data.content); break; case MsgType.TO_RECIVER: SendMessageToReciver(data.reciver, data.content); break; default: break; } } protected override void OnOpen() { _username = Context.QueryString["name"]; if (string.IsNullOrEmpty(_username)) { _username = this.ID; return; } _clients.Add(_username, this); Console.WriteLine("Client connected: " + _username); } protected override void OnClose(CloseEventArgs e) { _clients.Remove(_username); Console.WriteLine("Client connected: " + _username); } protected void SendMessageToReciver(string reciver,string message) { foreach (var client in _clients) { if (client.Key == reciver) { client.Value.Send(message); break; } } } protected void SendMessageToAll(string message) { foreach (var client in _clients) { client.Value.Send(message); } } } }
創(chuàng)建WebSocketMsgModel
namespace CaseAuto.helper.websocket { public class WebSocketMsgModel { public MsgType msgType { get; set; } public string content{ get; set; } public string sender { get; set; } public string reciver { get; set; } } public enum MsgType { NORMAL=0, GROUP=1, TO_RECIVER = 2, } }
使用
WebSocketHelper.Init();
二.客戶端
新建一個.net項目,如websocket.client
安裝包
Install-Package WebSocketSharp -Pre
使用
static void Main(string[] args) { using (var ws = new WebSocket("ws://127.0.0.1/caseInfo?name=c1")) { string? response = string.Empty; ws.OnMessage += (sender, e) => { response = e.Data; Console.WriteLine("Response: " + response); }; ws.Connect(); while (true) { string? request = Console.ReadLine(); ws.Send(request); Console.ReadKey(true); } } }
三.調試
- 啟動分別啟動服務端、客戶端
- 客戶端控制臺輸入【常規(guī)通訊測試】
{"msgType":0,"content":"hello"}
輸入后,回車,服務端返回
啟動apipost,新建websocket,輸入以下內容【群發(fā)】
ws://127.0.0.1/caseInfo?name=c2 {"msgType":1,"content":"hello456","reciver":"c1"}
點擊連接:
點擊發(fā)送:
4. 指定人發(fā)送
將apipost中發(fā)送的消息變?yōu)橄旅鎯热?,重新觀察apipost和自定義客戶端
{"msgType":2,"content":"hello c1","reciver":"c1"}
以上就是C#實現(xiàn)websocket雙向通信的示例代碼的詳細內容,更多關于C# websocket雙向通信的資料請關注腳本之家其它相關文章!