SignalR2 永久连接简单实例1

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();
            });
        }
    }
}

2.封装服务器端相应

    /// 
    /// 创建永久连接
    ///  Represents a connection between client and server.
    /// 
    public class EchoConnection : PersistentConnection
    {
        private static int _connections = 0;
        /// 
        /// 连接创建
        /// 
        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);
        }
        /// 
        /// 连接断开 
        /// 
        protected override Task OnDisconnected(IRequest request, string connectionId, bool stopCalled)
        {
            Interlocked.Decrement(ref _connections);
            return Connection.Broadcast(connectionId + "退出连接,已有连接数:" + _connections);
        }
        /// 
        /// 接受到消息
        /// 
        protected override Task OnReceived(IRequest request, string connectionId, string data)
        {
            var message = connectionId + "发送内容>>" + data;
            return Connection.Broadcast(message);
        }
    }

3.封装客户端相应





    
    Index
    
    


    

Echo service

SignalR2 永久连接简单实例1_第1张图片



你可能感兴趣的:(Asp.net,SignalR)