SingalR自托管(self-host)实例2-实现Wpf客户端和Web客户端矩形同步
源代码下载:http://git.oschina.net/tiama3798/SingleR_Demo/tree/SelfHost2/
集线器代码及说明:
IHub接口中定义的集线器的可用的属性和事件
IHubCallerConnectionContext<dynamic> Clients { get; set; } //所有的客户端连接
HubCallerContext Context { get; set; } //当前集线器上线文
IGroupManager Groups { get; set; } //当前集线器连接分组
Task OnConnected(); //当链接建立时触发
Task OnDisconnected(bool stopCalled); //当链接关闭或断开时触发
Task OnReconnected(); //当链接重新建立时触发
public class NumberHub : Hub
{
/// <summary>
/// 当前矩形位置发生改变时,通知其他客户端修改位置
/// </summary>
/// <param name="left"></param>
/// <param name="top"></param>
public void Abroast(double left, double top)
{
Console.WriteLine("服务器中转,left:{0},top:{1}",left,top);
//通知其他客户端修改位置
Clients.Others.change(left, top);
}
/// <summary>
/// 链接建立成功时触发
/// </summary>
/// <returns></returns>
public override Task OnConnected()
{
string content = string.Format("链接{0},建立成功", Context.ConnectionId);
var notify = (Task)Clients.All.wellcome(content);
Console.WriteLine(content);
return notify.ContinueWith(_ => notify);
}
/// <summary>
/// 链接关闭或超时时触发
/// </summary>
/// <param name="stopCalled">知否执行关闭操作</param>
/// <returns></returns>
public override Task OnDisconnected(bool stopCalled)
{
string content = stopCalled ? "链接关闭操作" : "超时自动关闭";
content = string.Format("链接{0},具体描述:{1}", Context.ConnectionId, content);
//通知所有其他客户端
var nodify = (Task)Clients.Others.wellcome(content);
return nodify.ContinueWith(_ => nodify);
}
}
运行结果: