SignalR2 永久連線簡單例項1
阿新 • • 發佈:2019-01-27
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>