Files
17168ERP/web/App_Code/SignalR_hub.cs
2025-08-29 01:27:25 +08:00

99 lines
3.3 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using System.Threading.Tasks;
using Microsoft.Owin;
public class signalRChat : Hub
{
// 呼叫所有使用者
//Clients.All.alertMessage(message);
// 呼叫除了自己的使用者
//Clients.Others.alertMessage(message);
// 呼叫所有使用者除了某個 ConnectionId 的使用者
//Clients.AllExcept(Context.ConnectionId).alertMessage(message);
// 呼叫自己
//Clients.Caller.alertMessage(message);
// 呼叫特定使用者
//Clients.Client(Context.ConnectionId).alertMessage(message);
// 呼叫群組使用者
//Clients.Group(groupId).alertMessage(message);
//宣告靜態類別,來儲存上線清單
public static class UserHandler
{
public static Dictionary<string, string> ConnectedIds = new Dictionary<string, string>();
}
//使用者連線時呼叫
public void userConnected(string name, string groupId)
{
//進行編碼防止XSS攻擊
name = HttpUtility.HtmlEncode(name);
//新增目前使用者至上線清單
UserHandler.ConnectedIds.Add(Context.ConnectionId, name);
//新增使用者至群組
Groups.Add(Context.ConnectionId, groupId);
}
//當使用者斷線時呼叫
public override Task OnDisconnected(bool stopCalled)
{
//當使用者離開時,移除在清單內的 ConnectionId
Clients.All.removeList(Context.ConnectionId);
UserHandler.ConnectedIds.Remove(Context.ConnectionId);
return base.OnDisconnected(stopCalled);
}
//若要使用前端來發話通知才需要下面的程式由後端發送請參考根目錄下的chat.aspx
/*
//發送訊息給所有人
public void sendAllMessage(string from, string message)
{
if (1==1) //這裡要驗證發話者(from)是否有權限發送
{
message = HttpUtility.HtmlEncode(message);
Clients.All.alertMessage(message); //alertMessage 為client端 function名稱
}
}
//發送訊息至特定使用者
public void sendMessage(string from, string connectId, string message)
{
if (1 == 1) //這裡要驗證發話者(from)是否有權限發送
{
message = HttpUtility.HtmlEncode(message);
Clients.Client(connectId).alertMessage(message); //alertMessage 為client端 function名稱
}
}
//發送訊息至特定使用者名稱
public void sendMessageByName(string from, string userName, string message)
{
if (1 == 1) //這裡要驗證發話者(from)是否有權限發送
{
message = HttpUtility.HtmlEncode(message);
var connectId = UserHandler.ConnectedIds.Where(p => p.Value == userName).FirstOrDefault().Key;
Clients.Client(connectId).alertMessage(message); //alertMessage 為client端 function名稱
}
}
//發送訊息至群組
public void sendGroupMessage(string from, string groupId, string message)
{
if (1 == 2) //這裡要驗證發話者(from)是否有權限發送
{
message = HttpUtility.HtmlEncode(message);
Clients.Group(groupId).alertMessage(message); //alertMessage 為client端 function名稱
}
}
*/
}