标签:
继续上一章的补充,这章介绍使用私聊的功能。主要通过一个方法 Clients.Client(Context.ConnectionId).showMessage(msg); SignalR框架就会给你找对对应的集线器客户端并调用客户端注册好的showMessage方法,下面具体实例和注意地方
创建一个User类,记录用户名字和集线器代理ID
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace SignalRTest { public class User { public string Name { get; set; } public string ConnectionId { get; set; } } }
TestHub代码
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Microsoft.AspNet.SignalR; using Microsoft.AspNet.SignalR.Hubs; using Newtonsoft.Json; namespace SignalRTest { //Hub的别名,方便前台调用 [HubName("testHHH")] public class TestHub : Hub { /// <summary> /// 用户列表,静态 /// </summary> public static List<User> list = new List<User>(); /// <summary> /// 模拟标示用户身份,静态 /// </summary> public static int i = 1; /// <summary> /// 重写连接方法,如果用户不存在,则新建用户 /// </summary> /// <returns></returns> public override System.Threading.Tasks.Task OnConnected() { var user = list.Where(u => u.ConnectionId == Context.ConnectionId).FirstOrDefault(); if (user == null) { //注册用户 list.Add(new User() { Name = "员工" + i, ConnectionId = Context.ConnectionId }); ++i; UpdatePageUserList(); } GetCurrentClientName(); return base.OnConnected(); } /// <summary> /// 重写断开方法,用户存在则删除用户 /// </summary> /// <returns></returns> public override System.Threading.Tasks.Task OnDisconnected() { var user = list.Where(u => u.ConnectionId == Context.ConnectionId).FirstOrDefault(); if (user != null) { list.Remove(user); UpdatePageUserList(); } return base.OnDisconnected(); } /// <summary> /// 更新页面用户列表,新增用户或者删除用户都需要更新一下 /// </summary> public void UpdatePageUserList() { var json = JsonConvert.SerializeObject(list); Clients.All.refreshUserList(json); } /// <summary> /// 私聊对象方法 /// </summary> /// <param name="ConnectionId"></param> public void StartChat(string ConnectionId, string content) { var user = list.Where(u => u.ConnectionId == ConnectionId).FirstOrDefault(); //判断用户是否存在,存在则发送 if (user != null) { //给指定用户发送,把自己的ID传过去用户找到当前哪个私聊对话框,因为可以打开很多个对话框 Clients.Client(ConnectionId).sendMessage(content + " " + DateTime.Now, Context.ConnectionId); //给自己发送,把用户的ID传给自己找到当前哪个私聊对话框,因为可以打开很多个对话框 Clients.Client(Context.ConnectionId).sendMessage(content + " " + DateTime.Now, ConnectionId); } else { Clients.Client(Context.ConnectionId).showMessage("该用户已离线"); } } /// <summary> /// 得到当前客户端的名字 /// </summary> public void GetCurrentClientName() { var user = list.Where(u => u.ConnectionId == Context.ConnectionId).FirstOrDefault(); Clients.Client(Context.ConnectionId).showCurrentClient(user.Name); } } }
客户端代码
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <script src="Scripts/jquery-1.10.2.js"></script> <script src="Scripts/jquery.signalR-2.0.0.js"></script> <!--这里要注意,这是虚拟目录,也就是你在OWIN Startup中注册的地址--> <script src="signalr/hubs"></script> </head> <body> <div><span>当前用户端名字:</span><span id="kkk"></span></div> <div style="width:200px;float:left;border:1px solid black;"> <ul id="userList"></ul> </div> <script type="text/javascript"> $(function () { //1.声明一个代理引用集线器,如果集线器没有取别名,则要小写$.connection.testHub;如果有别名则直接写别名就好了 var chatClient = $.connection.testHHH; //注册显示信息方法 chatClient.client.showMessage = function (msg) { alert(msg); } //注册获取当前客户端名字 chatClient.client.showCurrentClient = function (name) { $("#kkk").html(name); } //注册刷新用户列表方法 chatClient.client.refreshUserList = function (data) { var json = $.parseJSON(data); $("#userList").html(""); for (var i = 0; i < json.length; i++) { //动态加载内容到ul中 $("#userList").append($("<li>" + json[i].Name + " <input type=‘button‘ name=‘" + json[i].Name + "‘ class=‘" + json[i].ConnectionId + "‘ onclick=‘privateChat(this)‘ value=‘与他私聊‘ /></li>")); } } //注册发送消息 chatClient.client.sendMessage = function (msg, id) { $("#" + id + " ul").append($("<li>" + msg + "</li>")); } //3. 必须启动连接 $.connection.hub.start().done(function () { }); }); function privateChat(btn) { var ConnectionId = $(btn).attr("class"); var Name = $(btn).attr("name"); if ($("#" + ConnectionId).length > 0) { alert("已打开对话窗口"); } else { var str = "<div style=‘width:400px;float:left;border:1px solid black;‘ id=‘" + ConnectionId + "‘><div>" + "私聊对象:<input type=‘text‘ name=‘name‘ value=‘" + Name + "‘ />" + "<div>" + " <ul id=‘ul‘>" + " <li>开始群聊咯。。。。。。。。。。。。。</li>" + " </ul>" + " <input type=‘text‘ name=‘content‘ /><input type=‘button‘ name=‘btn‘ value=‘发送‘ onclick=‘sendMsg(this)‘ />" + " </div>" + " </div>" + " </div>"; $("body").append($(str)); } } function sendMsg(btn) { var connectionId = $(btn).parent().parent().parent().attr("id");//获取需要发送信息的员工连接ID var content = $(btn).siblings("input").val();//发送内容 var chatClient = $.connection.testHHH; //因为集线程变量作用范围原因,和上面的在$(function(){})中写的chatClient不在一个范围内了,所以在这里重新获取一次才能够调用后台的方法 chatClient.server.startChat(connectionId, content); } </script> </body> </html>
显示结果:
代码连接:http://pan.baidu.com/s/1o7oNSue
标签:
原文地址:http://www.cnblogs.com/kesimin/p/5082134.html