原文:用SignalR做类似QQ登录的应用
首先通过NuGet下载signalr包
在工程下新建一个类,继承Hub
public class DemoHub:Hub { public class Users { public string ConnectionId { get; set; } public string Name { get; set; } public string SId { get; set; } } //在线表 static List<Users> Connecteds = new List<Users>(); //验证 public void CheckedOnline(string name, string sid) { var id = Context.ConnectionId; if (string.IsNullOrEmpty(name)||string.IsNullOrEmpty(sid)) { Clients.Client(id).onExist("登录出错!"); } if (Connecteds.Count(x=>x.Name==name)==0) { Connecteds.Add(new Users() { ConnectionId = id, Name = name, SId = sid }); } else if(Connecteds.Count(x=>x.SId==sid)==0) { var oID = Connecteds.Find(x => x.Name == name).ConnectionId; Clients.Client(id).onExist("被登录"); var mod = Connecteds.FirstOrDefault(x => x.Name == name); Connecteds.Remove(mod); Connecteds.Add(new Users() { ConnectionId = id, Name = name, SId = sid }); } else if (Connecteds.Count(x=>x.SId==sid)==0) { Clients.Client(id).onExist("重复登录"); var mod = Connecteds.FirstOrDefault(x => x.Name == name); Connecteds.Remove(mod); } } //断开 public override System.Threading.Tasks.Task OnDisconnected(bool stopCalled) { var mod = Connecteds.FirstOrDefault(x=>x.ConnectionId==Context.ConnectionId); if (mod!=null) { Connecteds.Remove(mod); } return base.OnDisconnected(stopCalled); } //重连 public override System.Threading.Tasks.Task OnReconnected() { return base.OnReconnected(); } }
页面
@{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> <script src="~/Scripts/jquery-1.8.2.min.js"></script> <script src="~/Scripts/jquery.signalR-2.2.0.min.js"></script> <script src="@Url.Content("~/signalr/hubs")" type="text/javascript"></script> <script type="text/javascript"> var hub = $.connection.demoHub; $(function () { //start $.connection.hub.start().done(function () { hub.server.CheckedOnline("@ViewBag.Name","@ViewBag.sid"); }); hub.client.onExist = function (msg) { alert(msg); } //onReconnected hub.client.onReconnected = function () { hub = $.connection.demoHub; $.connection.hub.start().done(function () { hub.server.CheckedOnline("@ViewBag.Name", "@ViewBag.sid"); }); } }); </script>
好了基本完成,就差一个提示后退出。
菜鸟第一次发文写程序,对于程序的不足欢迎探讨。
时间: 2024-09-30 08:30:19