• <fieldset id="8imwq"><menu id="8imwq"></menu></fieldset>
  • <bdo id="8imwq"><input id="8imwq"></input></bdo>
    最新文章專題視頻專題問答1問答10問答100問答1000問答2000關鍵字專題1關鍵字專題50關鍵字專題500關鍵字專題1500TAG最新視頻文章推薦1 推薦3 推薦5 推薦7 推薦9 推薦11 推薦13 推薦15 推薦17 推薦19 推薦21 推薦23 推薦25 推薦27 推薦29 推薦31 推薦33 推薦35 推薦37視頻文章20視頻文章30視頻文章40視頻文章50視頻文章60 視頻文章70視頻文章80視頻文章90視頻文章100視頻文章120視頻文章140 視頻2關鍵字專題關鍵字專題tag2tag3文章專題文章專題2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章專題3
    問答文章1 問答文章501 問答文章1001 問答文章1501 問答文章2001 問答文章2501 問答文章3001 問答文章3501 問答文章4001 問答文章4501 問答文章5001 問答文章5501 問答文章6001 問答文章6501 問答文章7001 問答文章7501 問答文章8001 問答文章8501 問答文章9001 問答文章9501
    當前位置: 首頁 - 科技 - 知識百科 - 正文

    NetCore WebSocket即時通訊示例

    來源:懂視網 責編:小采 時間:2020-11-27 22:35:30
    文檔

    NetCore WebSocket即時通訊示例

    NetCore WebSocket即時通訊示例:NetCore WebSocket 即時通訊示例,供大家參考,具體內容如下 1.新建Netcore Web項目 2.創建簡易通訊協議 public class MsgTemplate { public string SenderID { get; set; } public string ReceiverID { get;
    推薦度:
    導讀NetCore WebSocket即時通訊示例:NetCore WebSocket 即時通訊示例,供大家參考,具體內容如下 1.新建Netcore Web項目 2.創建簡易通訊協議 public class MsgTemplate { public string SenderID { get; set; } public string ReceiverID { get;

    NetCore WebSocket 即時通訊示例,供大家參考,具體內容如下

    1.新建Netcore Web項目

    2.創建簡易通訊協議

    public class MsgTemplate
     {
     public string SenderID { get; set; }
     public string ReceiverID { get; set; }
     public string MessageType { get; set; }
     public string Content { get; set; }
     }
    
    

    SenderID發送者ID

    ReceiverID 接受者ID

    MessageType 消息類型  Text  Voice 等等

    Content 消息內容

    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運行在web端

    創建ionic3項目略過 新手可點這里查看  或者有Angular2/4項目竟然可直接往下看

    (1) 啟動Ionic項目

    當初創建ionic3項目時候遇到不少問題

    比如ionic-cli初始化項目失敗 切換到默認npmorg源就好了

    比如ionic serve失敗 打開代理允許FQ就好了

    啟動后界面是這樣式的

    (2) 創建聊天窗口dialog 具體布局實現 模塊加載略過直接進入websocket實現

    在這之前別忘了啟動web項目 否則會出現這樣情況 鏈接不到服務

    (3)dialog.ts具體實現

    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為我要發送的內容 比如"hello world"
     var msgObj = {
     SenderID: "222",
     ReceiverID: "111",
     MessageType: "text",
     Content: msg
     };
     this.ws.send(JSON.stringify(msgObj));
     }
    
    

    ws://localhost:56892?sid=222 這是websocke服務鏈接地址
    sid表示著我這個端的WebSocke唯一標識  找到這個key就可以找到我這個用戶端了 

    6.在web端也實現一個會話窗口

    <div class="container" style="width:90%;margin:0px auto;border:1px solid steelblue;">
     <div class="msg">
     <div id="msgs" style="height:200px;"></div>
     </div>
    
     <div 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" />
     </div>
    </div>
    
    
    <script>
     $(function () {
     $('.navbar-default').addClass('on');
    
     var userName = '@Model';
    
     var protocol = location.protocol === "https:" ? "wss:" : "ws:";
     var wsUri = protocol + "http://" + 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>
    
    

    基本開發完成 接下來看看效果

    7.web和webapp端對話

    8.webapp發送 web接收

    9.目前就實現了這么多  因為項目還涉及其它技術 暫時不開放源碼了

    聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com

    文檔

    NetCore WebSocket即時通訊示例

    NetCore WebSocket即時通訊示例:NetCore WebSocket 即時通訊示例,供大家參考,具體內容如下 1.新建Netcore Web項目 2.創建簡易通訊協議 public class MsgTemplate { public string SenderID { get; set; } public string ReceiverID { get;
    推薦度:
    標簽: net netcore core
    • 熱門焦點

    最新推薦

    猜你喜歡

    熱門推薦

    專題
    Top
    主站蜘蛛池模板: 亚洲精品无码精品mV在线观看| 亚洲国产精品成| 99久久人妻无码精品系列蜜桃| 国产视频精品免费视频| 国产精品美女免费视频观看| 亚洲AV永久无码精品水牛影视| 国产精品国产三级在线专区 | 亚洲?V乱码久久精品蜜桃| 国产精品久久久久天天影视| 亚洲av无码成人精品国产| 成人精品综合免费视频| 久久精品国产清高在天天线| 久久99精品久久久久久久不卡| 久久se精品一区精品二区国产| 精品亚洲永久免费精品| 国产精品亚洲片在线观看不卡| 亚洲国产精品一区二区九九| 久久99国产精品成人欧美| 国产成人精品久久综合| 欧美精品黑人巨大在线播放| 香蕉依依精品视频在线播放| 亚洲欧美日韩国产精品影院| 99久久国产综合精品成人影院| 91精品国产色综合久久| 孩交VIDEOS精品乱子| 亚洲av永久无码精品古装片 | 久久精品人人做人人爽电影蜜月| 亚洲精品无码永久在线观看 | 精品国产一区二区22| 国产精品午夜免费观看网站| 99re只有精品8中文| 一区二区三区精品| 国产成人99久久亚洲综合精品| 国产人成精品午夜在线观看| 国产精品露脸国语对白| 国产精品日本一区二区在线播放| 国产精品嫩草影院AV| 91精品国产9l久久久久| 99久久精品国产高清一区二区| 国产91精品在线| 亚洲国产精品久久66|