本篇文章主要介紹了.NET實現即時通信,WebSocket服務端實例 ,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟著小編過來看看吧
即時通訊常用手段
#1.第三方平台谷歌、騰訊環信等多如牛毛,其中谷歌即時通訊是免費的,但免費就是免費的並不好用。其他的一些第三方一般收費的,使用要則限流(1s/限制x條訊息)要么則限制用戶數。
但穩定性什麼都還不錯,又能將服務壓力甩出
2.System.Net.Sockets.Socket,也能寫一套較好的伺服器端。在.NET 4.5之前用較多,使用起來很麻煩。需要對資料包進行解析等操作(但看似網路上有對超長包的處理方法)
3.System.Net.WebSockets.WebSocket,這個,是.NET 4.5出來的東西,對伺服器環境也有所要求,IIS8以上。意味著Windows Server2008R2自帶的IIS不支持,Windows8及Server2012以上自備的IIS可以。本文主要將此方式的實例
完整流程
#1).用戶端請求連線
程式碼如下:
ws = new WebSocket('ws://' + window.location.hostname + ':' + window.location.port + '/Handler1.ashx?user=' + $("#user" ).val());
2).服務端取得連線物件並儲存到連線池中
CONNECT_POOL.Add(user, socket);
3).連線物件開始監聽(每個客戶端與伺服器保存長連結)
程式碼如下:
WebSocketReceiveResult result = await socket.ReceiveAsync(buffer, CancellationToken.None);
4).客戶端A發送訊息給B
ws.send($("#to").val() + "|" + $('#content').val());
string userMsg = Encoding.UTF8.GetString(buffer.Array, 0, result.Count);
WebSocket destSocket = CONNECT_POOL[descUser]; await destSocket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);
WebSocketReceiveResult result = await socket.ReceiveAsync(buffer, CancellationToken.None);
ws.onmessage = function (evt) { $('#msg').append('<p>' + evt.data + '</p>'); }
<script> var ws; $().ready(function () { $('#conn').click(function () { ws = new WebSocket('ws://' + window.location.hostname + ':' + window.location.port + '/Handler1.ashx?user=' + $("#user").val()); $('#msg').append('<p>正在连接</p>'); ws.onopen = function () { $('#msg').append('<p>已经连接</p>'); } ws.onmessage = function (evt) { $('#msg').append('<p>' + evt.data + '</p>'); } ws.onerror = function (evt) { $('#msg').append('<p>' + JSON.stringify(evt) + '</p>'); } ws.onclose = function () { $('#msg').append('<p>已经关闭</p>'); } }); $('#close').click(function () { ws.close(); }); $('#send').click(function () { if (ws.readyState == WebSocket.OPEN) { ws.send($("#to").val() + "|" + $(&#39;#content&#39;).val()); } else { $('#tips').text('连接已经关闭'); } }); }); </script>
目的用户
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net.WebSockets; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Web; using System.Web.WebSockets; namespace WebApplication1 { /// <summary> /// 离线消息 /// </summary> public class MessageInfo { public MessageInfo(DateTime _MsgTime, ArraySegment<byte> _MsgContent) { MsgTime = _MsgTime; MsgContent = _MsgContent; } public DateTime MsgTime { get; set; } public ArraySegment<byte> MsgContent { get; set; } } /// <summary> /// Handler1 的摘要说明 /// </summary> public class Handler1 : IHttpHandler { private static Dictionary<string, WebSocket> CONNECT_POOL = new Dictionary<string, WebSocket>();//用户连接池 private static Dictionary<string, List<MessageInfo>> MESSAGE_POOL = new Dictionary<string, List<MessageInfo>>();//离线消息池 public void ProcessRequest(HttpContext context) { if (context.IsWebSocketRequest) { context.AcceptWebSocketRequest(ProcessChat); } } private async Task ProcessChat(AspNetWebSocketContext context) { WebSocket socket = context.WebSocket; string user = context.QueryString["user"].ToString(); try { #region 用户添加连接池 //第一次open时,添加到连接池中 if (!CONNECT_POOL.ContainsKey(user)) CONNECT_POOL.Add(user, socket);//不存在,添加 else if (socket != CONNECT_POOL[user])//当前对象不一致,更新 CONNECT_POOL[user] = socket; #endregion #region 离线消息处理 if (MESSAGE_POOL.ContainsKey(user)) { List<MessageInfo> msgs = MESSAGE_POOL[user]; foreach (MessageInfo item in msgs) { await socket.SendAsync(item.MsgContent, WebSocketMessageType.Text, true, CancellationToken.None); } MESSAGE_POOL.Remove(user);//移除离线消息 } #endregion string descUser = string.Empty;//目的用户 while (true) { if (socket.State == WebSocketState.Open) { ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[2048]); WebSocketReceiveResult result = await socket.ReceiveAsync(buffer, CancellationToken.None); #region 消息处理(字符截取、消息转发) try { #region 关闭Socket处理,删除连接池 if (socket.State != WebSocketState.Open)//连接关闭 { if (CONNECT_POOL.ContainsKey(user)) CONNECT_POOL.Remove(user);//删除连接池 break; } #endregion string userMsg = Encoding.UTF8.GetString(buffer.Array, 0, result.Count);//发送过来的消息 string[] msgList = userMsg.Split('|'); if (msgList.Length == 2) { if (msgList[0].Trim().Length > 0) descUser = msgList[0].Trim();//记录消息目的用户 buffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(msgList[1])); } else buffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(userMsg)); if (CONNECT_POOL.ContainsKey(descUser))//判断客户端是否在线 { WebSocket destSocket = CONNECT_POOL[descUser];//目的客户端 if (destSocket != null && destSocket.State == WebSocketState.Open) await destSocket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None); } else { Task.Run(() => { if (!MESSAGE_POOL.ContainsKey(descUser))//将用户添加至离线消息池中 MESSAGE_POOL.Add(descUser, new List<MessageInfo>()); MESSAGE_POOL[descUser].Add(new MessageInfo(DateTime.Now, buffer));//添加离线消息 }); } } catch (Exception exs) { //消息转发异常处理,本次消息忽略 继续监听接下来的消息 } #endregion } else { break; } }//while end } catch (Exception ex) { //整体异常处理 if (CONNECT_POOL.ContainsKey(user)) CONNECT_POOL.Remove(user); } } public bool IsReusable { get { return false; } } } }
以上是.NET實作WebSocket服務端即時通訊的實例詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!