SignalR2 永久连接简单实例1

时间:2021-08-11 03:41:57

1.启动路由注册

[assembly: OwinStartupAttribute(typeof(SignalRDemo1.Startup))]
namespace SignalRDemo1
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
            //注册服务器端相应地址
            app.Map("/realtime/echo", map =>
            {
                map.UseCors(CorsOptions.AllowAll);
                map.RunSignalR<EchoConnection>();
            });
        }
    }
}

2.封装服务器端相应

    /// <summary>
    /// 创建永久连接
    ///  Represents a connection between client and server.
    /// </summary>
    public class EchoConnection : PersistentConnection
    {
        private static int _connections = 0;
        /// <summary>
        /// 连接创建
        /// </summary>
        protected override async Task OnConnected(IRequest request, string connectionID)
        {
            Interlocked.Increment(ref _connections);
            await Connection.Send(connectionID, "双向连接成功,连接ID:" + connectionID);
            //广播消息
            await Connection.Broadcast("新的连接加入,连接ID:" + connectionID + ",已有连接数:" + _connections);
        }
        /// <summary>
        /// 连接断开 
        /// </summary>
        protected override Task OnDisconnected(IRequest request, string connectionId, bool stopCalled)
        {
            Interlocked.Decrement(ref _connections);
            return Connection.Broadcast(connectionId + "退出连接,已有连接数:" + _connections);
        }
        /// <summary>
        /// 接受到消息
        /// </summary>
        protected override Task OnReceived(IRequest request, string connectionId, string data)
        {
            var message = connectionId + "发送内容>>" + data;
            return Connection.Broadcast(message);
        }
    }

3.封装客户端相应

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script src="~/Scripts/jquery.signalR-2.2.0.js"></script>
</head>
<body>
    <div>
        <h1>Echo service</h1>
        <div>
            <input type="text" id="text" />
            <button id="send">Send</button>
        </div>
        <script>
            var connection = $.connection("/realtime/echo");
            connection.logging = true;
            //客户端接收消息
            connection.received(function (data) {
                $(document.body).append(data+"<br/>");
            });
            //连接错误处理
            connection.error(function (err) {
                alert('与服务器连接报错:'+err.message);
            });
            //连接成功
            connection.start().done(function () {
                $('#send').click(function () {
                    var val = $('#text').val();
                    //向服务器端发送消息
                    connection.send(val);
                });
            });
        </script>
    </div>
</body>
</html>
SignalR2 永久连接简单实例1