.net使用websocket

客户端:

<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>

    <script src="Scripts/jquery-3.4.1.min.js"></script>
    <script>
        var ws;
        $().ready(function () {
            $('#conn').click(function () {
                ws = new WebSocket('ws://' + window.location.hostname + ':' + window.location.port + '/Handler1.ashx');
                $('#tips').text('正在连接');
                ws.onopen = function () {
                    $('#tips').text('已经连接');
                }
                ws.onmessage = function (evt) {
                    $('#tips').html($('#tips').html() + '<br/>' + evt.data);
                }
                ws.onerror = function (evt) {
                    $('#tips').text(JSON.stringify(evt));
                }
                ws.onclose = function () {
                    $('#tips').text('已经关闭');
                }
            });

            $('#close').click(function () {
                ws.close();
            });

            $('#send').click(function () {
                if (ws.readyState == WebSocket.OPEN) {
                    ws.send($('#content').val());
                }
                else {
                    $('#tips').text('连接已经关闭');
                }
            });

        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
             
            
            <br />
            <input id="conn" type="button" value="连接" />
            <input id="close" type="button" value="关闭" />
            <span id="tips"></span>
            <input id="content" type="text" />
            <input id="send" type="button" value="发送" />
        </div>
    </form>
</body>

服务端(一般处理程序):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.WebSockets;
namespace WebApplication1
{
    /// <summary>
    /// Handler1 的摘要说明
    /// </summary>
    public class Handler1 : IHttpHandler
    {

        public static List<WebSocket> list = new List<WebSocket>();
        public void ProcessRequest(HttpContext context)
        {
            if (context.IsWebSocketRequest)
            {
                context.AcceptWebSocketRequest(ProcessChat);
            }
        }

        private async System.Threading.Tasks.Task ProcessChat(AspNetWebSocketContext context)
        {
       
            WebSocket socket = context.WebSocket;

            if (!list.Any(x=>x==socket)) 
            {
                list.Add(socket);
            }
           
            while (true)
            {
                ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[2048]);
                WebSocketReceiveResult result = await socket.ReceiveAsync(buffer, CancellationToken.None);
                if (socket.State == WebSocketState.Open)
                {
                  
                    string userMsg = Encoding.UTF8.GetString(buffer.Array, 0, result.Count);
                    userMsg = "你发送了:" + userMsg + "" + DateTime.Now.ToLongTimeString();
                    buffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(userMsg));
                

                    foreach (var item in list) 
                    {
                        if (item==socket) 
                        {
                            await item.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);
                        }
                    }
                }
                else
                {   
                    //关闭连接
                    if (result.MessageType == WebSocketMessageType.Close)
                    {
                        await socket.CloseAsync(WebSocketCloseStatus.Empty, string.Empty, CancellationToken.None);//如果client发起close请求,对client进行ack
                        list.Remove(socket);
                        break;
                    }
                     
                }
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

 源码下载:包含服务端和bs/cs客户端实现

posted @ 2023-03-13 15:27  gds111789  阅读(126)  评论(0编辑  收藏  举报