您好,登錄后才能下訂單哦!
這篇文章主要為大家展示了“如何制作NetCore WebSocket即時(shí)通訊”,內(nèi)容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“如何制作NetCore WebSocket即時(shí)通訊”這篇文章吧。
NetCore WebSocket 即時(shí)通訊示例,供大家參考,具體內(nèi)容如下
1.新建Netcore Web項(xiàng)目
2.創(chuàng)建簡易通訊協(xié)議
public class MsgTemplate { public string SenderID { get; set; } public string ReceiverID { get; set; } public string MessageType { get; set; } public string Content { get; set; } }
SenderID發(fā)送者ID
ReceiverID 接受者ID
MessageType 消息類型 Text Voice 等等
Content 消息內(nèi)容
3.添加中間件ChatWebSocketMiddleware
public class ChatWebSocketMiddleware { private static ConcurrentDictionary<string, System.Net.WebSockets.WebSocket> _sockets = new ConcurrentDictionary<string, System.Net.WebSockets.WebSocket>(); private readonly RequestDelegate _next; public ChatWebSocketMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { if (!context.WebSockets.IsWebSocketRequest) { await _next.Invoke(context); return; } System.Net.WebSockets.WebSocket dummy; CancellationToken ct = context.RequestAborted; var currentSocket = await context.WebSockets.AcceptWebSocketAsync(); //string socketId = Guid.NewGuid().ToString(); string socketId = context.Request.Query["sid"].ToString(); if (!_sockets.ContainsKey(socketId)) { _sockets.TryAdd(socketId, currentSocket); } //_sockets.TryRemove(socketId, out dummy); //_sockets.TryAdd(socketId, currentSocket); while (true) { if (ct.IsCancellationRequested) { break; } string response = await ReceiveStringAsync(currentSocket, ct); MsgTemplate msg = JsonConvert.DeserializeObject<MsgTemplate>(response); if (string.IsNullOrEmpty(response)) { if (currentSocket.State != WebSocketState.Open) { break; } continue; } foreach (var socket in _sockets) { if (socket.Value.State != WebSocketState.Open) { continue; } if (socket.Key == msg.ReceiverID || socket.Key == socketId) { await SendStringAsync(socket.Value, JsonConvert.SerializeObject(msg), ct); } } } //_sockets.TryRemove(socketId, out dummy); await currentSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closing", ct); currentSocket.Dispose(); } private static Task SendStringAsync(System.Net.WebSockets.WebSocket socket, string data, CancellationToken ct = default(CancellationToken)) { var buffer = Encoding.UTF8.GetBytes(data); var segment = new ArraySegment<byte>(buffer); return socket.SendAsync(segment, WebSocketMessageType.Text, true, ct); } private static async Task<string> ReceiveStringAsync(System.Net.WebSockets.WebSocket socket, CancellationToken ct = default(CancellationToken)) { var buffer = new ArraySegment<byte>(new byte[8192]); using (var ms = new MemoryStream()) { WebSocketReceiveResult result; do { ct.ThrowIfCancellationRequested(); result = await socket.ReceiveAsync(buffer, ct); ms.Write(buffer.Array, buffer.Offset, result.Count); } while (!result.EndOfMessage); ms.Seek(0, SeekOrigin.Begin); if (result.MessageType != WebSocketMessageType.Text) { return null; } using (var reader = new StreamReader(ms, Encoding.UTF8)) { return await reader.ReadToEndAsync(); } } } }
控制只有接收者才能收到消息
if (socket.Key == msg.ReceiverID || socket.Key == socketId) { await SendStringAsync(socket.Value,JsonConvert.SerializeObject(msg), ct); }
4.在Startup.cs中使用中間件
app.UseWebSockets(); app.UseMiddleware<ChatWebSocketMiddleware>();
5.建立移動端測試示例 這里采用Ionic3運(yùn)行在web端
創(chuàng)建ionic3項(xiàng)目略過 新手可點(diǎn)這里查看 或者有Angular2/4項(xiàng)目竟然可直接往下看
(1) 啟動Ionic項(xiàng)目
當(dāng)初創(chuàng)建ionic3項(xiàng)目時(shí)候遇到不少問題
比如ionic-cli初始化項(xiàng)目失敗 切換到默認(rèn)npmorg源就好了
比如ionic serve失敗 打開代理允許FQ就好了
啟動后界面是這樣式的
(2) 創(chuàng)建聊天窗口dialog 具體布局實(shí)現(xiàn) 模塊加載略過直接進(jìn)入websocket實(shí)現(xiàn)
在這之前別忘了啟動web項(xiàng)目 否則會出現(xiàn)這樣情況 鏈接不到服務(wù)
(3)dialog.ts具體實(shí)現(xiàn)
export class Dialog { private ws: any; private msgArr: Array<any>; constructor(private httpService: HttpService) { this.msgArr = []; } ionViewDidEnter() { if (!this.ws) { this.ws = new WebSocket("ws://localhost:56892?sid=222"); this.ws.onopen = () => { console.log('open'); }; this.ws.onmessage = (event) => { console.log('new message: ' + event.data); var msgObj = JSON.parse(event.data); this.msgArr.push(msgObj);; }; this.ws.onerror = () => { console.log('error occurred!'); }; this.ws.onclose = (event) => { console.log('close code=' + event.code); }; } } sendMsg(msg) {//msg為我要發(fā)送的內(nèi)容 比如"hello world" var msgObj = { SenderID: "222", ReceiverID: "111", MessageType: "text", Content: msg }; this.ws.send(JSON.stringify(msgObj)); }
ws://localhost:56892?sid=222 這是websocke服務(wù)鏈接地址
sid表示著我這個(gè)端的WebSocke唯一標(biāo)識 找到這個(gè)key就可以找到我這個(gè)用戶端了
6.在web端也實(shí)現(xiàn)一個(gè)會話窗口
<p class="container" style="width:90%;margin:0px auto;border:1px solid steelblue;"> <p class="msg"> <p id="msgs" style="height:200px;"></p> </p> <p style="display:block;width:100%"> <input type="text" style="max-width:unset;width:100%;max-width:100%" id="MessageField" placeholder="type message and press enter" /> </p> </p>
<script> $(function () { $('.navbar-default').addClass('on'); var userName = '@Model'; var protocol = location.protocol === "https:" ? "wss:" : "ws:"; var wsUri = protocol + "//" + window.location.host + "?sid=111"; var socket = new WebSocket(wsUri); socket.onopen = e => { console.log("socket opened", e); }; socket.onclose = function (e) { console.log("socket closed", e); }; socket.onmessage = function (e) { console.log(e); var msgObj = JSON.parse(e.data); $('#msgs').append(msgObj.Content + '<br />'); }; socket.onerror = function (e) { console.error(e.data); }; $('#MessageField').keypress(function (e) { if (e.which != 13) { return; } e.preventDefault(); var message = $('#MessageField').val(); var msgObj = { SenderID:"111", ReceiverID:"222", MessageType: "text", Content: message }; socket.send(JSON.stringify(msgObj)); $('#MessageField').val(''); }); }); </script>
基本開發(fā)完成 接下來看看效果
7.web和webapp端對話
8.webapp發(fā)送 web接收
以上是“如何制作NetCore WebSocket即時(shí)通訊”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。