using Microsoft.AspNet.SignalR;
|
using System;
|
using System.Collections.Generic;
|
using System.Data;
|
using System.Linq;
|
using System.Threading.Tasks;
|
using System.Web;
|
using VueWebApi.Models;
|
using VueWebApi.Tools;
|
|
namespace VueWebApi.Hubs
|
{
|
public class ChatHub2 : Hub
|
{
|
/// < summary>
|
///
|
/// </ summary>
|
public static List<string> Users = new List<string>();
|
|
/// <summary>
|
/// 未连接事件
|
/// </summary>
|
/// <returns></returns>
|
public override Task OnConnected()
|
{
|
LogHelper.WriteLogData("执行OnConnected");
|
string clientId = GetClientId();
|
if (Users.IndexOf(clientId) == -1)
|
{
|
Users.Add(clientId);
|
}
|
Send(Users.Count);
|
var context = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
|
context.Clients.Client(clientId).updateUserName(clientId);
|
return base.OnConnected();
|
}
|
|
/// <summary>
|
/// 重新连接事件
|
/// </summary>
|
/// <returns></returns>
|
public override Task OnReconnected()
|
{
|
LogHelper.WriteLogData("执行OnReconnected");
|
string clientId = GetClientId();
|
if (Users.IndexOf(clientId) == -1)
|
{
|
Users.Add(clientId);
|
}
|
Send(Users.Count);
|
return base.OnReconnected();
|
}
|
|
/// <summary>
|
/// 断开连接事件
|
/// </summary>
|
/// <param name="stopCalled"></param>
|
/// <returns></returns>
|
public override Task OnDisconnected(bool stopCalled)
|
{
|
LogHelper.WriteLogData("执行OnDisconnected");
|
string clientId = GetClientId();
|
|
if (Users.IndexOf(clientId) > -1)
|
{
|
Users.Remove(clientId);
|
}
|
Send(Users.Count);
|
return base.OnDisconnected(stopCalled);
|
}
|
|
/// <summary>
|
/// 这对于每个客户端都是唯一的,用于标识连接。
|
/// </summary>
|
/// <returns></returns>
|
private string GetClientId()
|
{
|
string clientId = "";
|
|
//从应用程序传递的客户ID
|
if (Context.QueryString["clientId"] != null)
|
{
|
clientId = this.Context.QueryString["clientId"];
|
}
|
|
if (string.IsNullOrEmpty(clientId.Trim()))
|
{
|
clientId = Context.ConnectionId;
|
}
|
LogHelper.WriteLogData("执行1:" + clientId);
|
return clientId;
|
}
|
|
/// <summary>
|
/// Sends the update user count to the listening view.
|
/// </summary>
|
/// <param name="count">
|
/// The count.
|
/// </param>
|
public void Send(int count)
|
{
|
LogHelper.WriteLogData("执行count:" + count);
|
// Call the addNewMessageToPage method to update clients.
|
var context = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
|
context.Clients.All.updateUsersOnlineCount(count);
|
}
|
/// <summary>
|
/// 自己写的一个服务端方法Hello.
|
/// </summary>
|
/// <param name="msg">参数
|
/// </param>
|
public void Hello(string msg)
|
{
|
LogHelper.WriteLogData("执行msg:" + msg);
|
var context = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
|
context.Clients.All.clientMethod("server:" + msg);
|
}
|
|
}
|
}
|