Files
DanMuRead/BarrageGrab/WsBarrageService.cs
T

664 lines
24 KiB
C#
Raw Normal View History

2022-10-06 17:44:08 +08:00
using System;
using System.Collections.Generic;
using System.Linq;
2023-08-17 20:37:22 +08:00
using System.Net;
2022-10-06 17:44:08 +08:00
using System.Net.WebSockets;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using Fleck;
using Newtonsoft.Json;
2023-08-17 20:37:22 +08:00
using BarrageGrab.Modles;
using Newtonsoft.Json.Linq;
2023-08-17 20:37:22 +08:00
using System.Net.Http;
using System.IO.Compression;
using System.IO;
using BarrageGrab.Modles.JsonEntity;
using BarrageGrab.Modles.ProtoEntity;
2023-11-23 16:43:21 +08:00
using System.Drawing;
2024-03-10 03:44:13 +08:00
using System.Collections.Concurrent;
2022-10-06 17:44:08 +08:00
namespace BarrageGrab
{
/// <summary>
/// 弹幕服务
/// </summary>
2023-08-17 20:37:22 +08:00
public class WsBarrageService
2023-12-17 23:56:10 +08:00
{
2024-03-29 11:20:17 +08:00
WebSocketServer socketServer; //Ws服务器对象
Dictionary<string, UserState> socketList = new Dictionary<string, UserState>(); //客户端列表
ConcurrentDictionary<string, Tuple<int, DateTime>> giftCountCache = new ConcurrentDictionary<string, Tuple<int, DateTime>>();//礼物计数缓存
Timer dieout = new Timer(10000);//离线客户端清理计时器
Timer giftCountTimer = new Timer(10000);//礼物缓存清理计时器
WssBarrageGrab grab = new WssBarrageGrab();//弹幕解析器核心
Appsetting Appsetting = Appsetting.Current;//全局配置文件实例
static int printCount = 0; //控制台输出计数,用于判断清理控制台
2023-08-17 20:37:22 +08:00
2023-03-09 00:33:03 +08:00
2023-11-16 09:26:40 +08:00
/// <summary>
/// WS服务器启动地址
/// </summary>
public string ServerLocation { get { return socketServer.Location; } }
2023-11-23 16:43:21 +08:00
/// <summary>
/// 数据内核
/// </summary>
public WssBarrageGrab Grab { get { return grab; } }
/// <summary>
/// 控制台打印事件
/// </summary>
public event EventHandler<PrintEventArgs> OnPrint;
2024-03-29 11:20:17 +08:00
/// <summary>
/// 服务关闭后触发
/// </summary>
public event EventHandler OnClose;
/// <summary>
/// 消息包装完成后触发
/// </summary>
public event EventHandler<PackMsgEventArgs> OnPackMessage;
2023-03-09 00:33:03 +08:00
public WsBarrageService()
2022-10-06 17:44:08 +08:00
{
2023-08-17 20:37:22 +08:00
var socket = new WebSocketServer($"ws://0.0.0.0:{Appsetting.WsProt}");
2022-10-06 17:44:08 +08:00
socket.RestartAfterListenError = true;//异常重启
dieout.Elapsed += Dieout_Elapsed;
giftCountTimer.Elapsed += GiftCountTimer_Elapsed;
2022-10-06 17:44:08 +08:00
this.grab.OnChatMessage += Grab_OnChatMessage;
this.grab.OnLikeMessage += Grab_OnLikeMessage;
this.grab.OnMemberMessage += Grab_OnMemberMessage;
this.grab.OnSocialMessage += Grab_OnSocialMessage;
this.grab.OnSocialMessage += Grab_OnShardMessage;
2022-10-06 17:44:08 +08:00
this.grab.OnGiftMessage += Grab_OnGiftMessage;
this.grab.OnRoomUserSeqMessage += Grab_OnRoomUserSeqMessage;
this.grab.OnFansclubMessage += Grab_OnFansclubMessage; ;
this.grab.OnControlMessage += Grab_OnControlMessage;
2022-10-06 17:44:08 +08:00
this.socketServer = socket;
//dieout.Start();
giftCountTimer.Start();
}
2024-03-29 11:20:17 +08:00
//礼物缓存清理计时器回调
private void GiftCountTimer_Elapsed(object sender, ElapsedEventArgs e)
{
var now = DateTime.Now;
var timeOutKeys = giftCountCache.Where(w => w.Value.Item2 < now.AddSeconds(-10) || w.Value == null).Select(s => s.Key).ToList();
//淘汰过期的礼物计数缓存
lock (giftCountCache)
{
timeOutKeys.ForEach(key =>
{
2024-03-29 11:20:17 +08:00
Tuple<int, DateTime> _;
2024-03-10 03:44:13 +08:00
giftCountCache.TryRemove(key, out _);
});
}
2022-10-06 17:44:08 +08:00
}
2024-03-29 11:20:17 +08:00
//心跳淘汰计时器回调
private void Dieout_Elapsed(object sender, ElapsedEventArgs e)
{
var now = DateTime.Now;
var dieoutKvs = socketList.Where(w => w.Value.LastPing.AddSeconds(dieout.Interval * 3) < now).ToList();
dieoutKvs.ForEach(f => f.Value.Socket.Close());
}
//判断Rommid是否符合拦截规则
2023-03-09 00:33:03 +08:00
private bool CheckRoomId(long roomid)
{
2024-03-10 03:44:13 +08:00
if (!Appsetting.Current.WebRoomIds.Any()) return true;
var webrid = AppRuntime.RoomCaches.GetCachedWebRoomid(roomid.ToString());
if (webrid <= 0) return true;
2024-03-29 11:20:17 +08:00
2024-03-10 03:44:13 +08:00
return Appsetting.Current.WebRoomIds.Contains(webrid);
2023-03-09 00:33:03 +08:00
}
2023-11-14 20:29:18 +08:00
2023-03-09 00:33:03 +08:00
//解析用户
2023-08-17 20:37:22 +08:00
private MsgUser GetUser(User data)
2022-10-06 17:44:08 +08:00
{
2023-12-17 23:56:10 +08:00
if (data == null) return null;
2022-10-06 17:44:08 +08:00
MsgUser user = new MsgUser()
{
2023-03-09 00:33:03 +08:00
DisplayId = data.displayId,
2023-04-24 21:39:22 +08:00
ShortId = data.shortId,
2023-03-09 00:33:03 +08:00
Gender = data.Gender,
Id = data.Id,
Level = data.Level,
2023-12-17 23:56:10 +08:00
PayLevel = (int)(data.payGrade?.Level ?? -1),
Nickname = data.Nickname ?? "用户" + data.displayId,
HeadImgUrl = data.avatarThumb?.urlLists?.FirstOrDefault() ?? "",
2023-04-24 21:39:22 +08:00
SecUid = data.sec_uid,
2023-12-17 23:56:10 +08:00
FollowerCount = data.followInfo?.followerCount ?? -1,
FollowingCount = data.followInfo?.followingCount ?? -1,
FollowStatus = data.followInfo?.followStatus ?? -1,
2022-10-06 17:44:08 +08:00
};
2023-04-01 00:07:17 +08:00
user.FansClub = new FansClubInfo()
{
2023-04-01 00:07:17 +08:00
ClubName = "",
Level = 0
};
if (data.fansClub != null && data.fansClub.Data != null)
2023-04-01 00:07:17 +08:00
{
user.FansClub.ClubName = data.fansClub.Data.clubName;
2023-04-24 21:39:22 +08:00
user.FansClub.Level = data.fansClub.Data.Level;
}
2022-10-06 17:44:08 +08:00
return user;
}
2024-03-29 11:20:17 +08:00
//打印消息
private void PrintMsg(Msg msg, PackMsgType barType)
2023-12-17 23:56:10 +08:00
{
var rinfo = AppRuntime.RoomCaches.GetCachedWebRoomInfo(msg.RoomId.ToString());
var roomName = (rinfo?.Owner?.Nickname ?? ("直播间" + (msg.WebRoomId == 0 ? msg.RoomId : msg.WebRoomId)));
var text = $"{DateTime.Now.ToString("HH:mm:ss")} [{roomName}] [{barType}]";
if (msg.User != null)
{
text += $" [{msg.User?.GenderToString()}] ";
}
2023-11-23 16:43:21 +08:00
ConsoleColor color = Appsetting.Current.ColorMap[barType].Item1;
var append = msg.Content;
switch (barType)
{
2023-12-17 23:56:10 +08:00
case PackMsgType.弹幕消息: append = $"{msg?.User?.Nickname}: {msg.Content}"; break;
case PackMsgType.下播: append = $"直播已结束"; break;
default: break;
}
2023-12-17 23:56:10 +08:00
text += append;
2023-11-23 16:43:21 +08:00
if (Appsetting.Current.BarrageLog)
{
Logger.LogBarrage(barType, msg);
}
if (!Appsetting.PrintBarrage) return;
if (Appsetting.Current.PrintFilter.Any() && !Appsetting.Current.PrintFilter.Contains(barType.GetHashCode())) return;
OnPrint?.Invoke(this, new PrintEventArgs()
{
Color = color,
Message = text,
MsgType = barType
});
2024-03-29 11:20:17 +08:00
if (++printCount > 10000)
{
Console.Clear();
2024-03-10 03:44:13 +08:00
Logger.PrintColor("控制台已清理");
2024-03-29 11:20:17 +08:00
printCount = 0;
}
2024-03-10 03:44:13 +08:00
Logger.PrintColor(text + "\n", color);
}
2024-03-29 11:20:17 +08:00
//发送消息包装事件
private void FirePack(Msg msg, PackMsgType barType)
{
if (OnPackMessage == null) return;
var arg = new PackMsgEventArgs()
{
MsgType = barType,
Message = msg
};
//异步执行
Task.Run(() => OnPackMessage(this, arg));
}
//粉丝团
private void Grab_OnFansclubMessage(object sender, WssBarrageGrab.RoomMessageEventArgs<FansclubMessage> e)
{
var msg = e.Message;
if (!CheckRoomId(msg.Common.roomId)) return;
var enty = new FansclubMsg()
{
MsgId = msg.Common.msgId,
Content = msg.Content,
RoomId = msg.Common.roomId,
WebRoomId = AppRuntime.RoomCaches.GetCachedWebRoomid(msg.Common.roomId.ToString()),
Type = msg.Type,
User = GetUser(msg.User)
};
2023-04-24 21:39:22 +08:00
enty.Level = enty.User.FansClub.Level;
2023-11-14 20:29:18 +08:00
var msgType = PackMsgType.粉丝团消息;
2024-03-29 11:20:17 +08:00
FirePack(enty, msgType);
PrintMsg(enty, msgType);
2023-11-14 20:29:18 +08:00
Broadcast(new BarrageMsgPack(enty.ToJson(), msgType, e.Process));
}
2023-03-09 00:33:03 +08:00
//统计消息
private void Grab_OnRoomUserSeqMessage(object sender, WssBarrageGrab.RoomMessageEventArgs<RoomUserSeqMessage> e)
{
var msg = e.Message;
if (!CheckRoomId(msg.Common.roomId)) return;
var enty = new UserSeqMsg()
{
MsgId = msg.Common.msgId,
OnlineUserCount = msg.Total,
TotalUserCount = msg.totalUser,
TotalUserCountStr = msg.totalPvForAnchor,
OnlineUserCountStr = msg.onlineUserForAnchor,
RoomId = msg.Common.roomId,
WebRoomId = AppRuntime.RoomCaches.GetCachedWebRoomid(msg.Common.roomId.ToString()),
Content = $"当前直播间人数 {msg.onlineUserForAnchor},累计直播间人数 {msg.totalPvForAnchor}",
User = null
};
2023-11-14 20:29:18 +08:00
var msgType = PackMsgType.直播间统计;
2024-03-29 11:20:17 +08:00
FirePack(enty, msgType);
PrintMsg(enty, msgType);
var pack = new BarrageMsgPack(enty.ToJson(), msgType, e.Process);
Broadcast(pack);
}
2023-03-09 00:33:03 +08:00
//礼物
private void Grab_OnGiftMessage(object sender, WssBarrageGrab.RoomMessageEventArgs<GiftMessage> e)
2022-10-06 17:44:08 +08:00
{
var msg = e.Message;
if (!CheckRoomId(msg.Common.roomId)) return;
var key = msg.Common.roomId + "-" + msg.giftId + "-" + msg.groupId.ToString();
int currCount = (int)msg.repeatCount;
2024-03-10 03:44:13 +08:00
int lastCount = 0;
//Combo 为1时,表示为可连击礼物
if (msg.Gift.Combo)
2022-10-06 17:44:08 +08:00
{
2024-03-10 03:44:13 +08:00
//判断礼物重复
if (msg.repeatEnd == 1)
{
2024-03-10 03:44:13 +08:00
//清除缓存中的key
if (msg.groupId > 0 && giftCountCache.ContainsKey(key))
{
2024-03-29 11:20:17 +08:00
Tuple<int, DateTime> _;
2024-03-10 03:44:13 +08:00
giftCountCache.TryRemove(key, out _);
}
return;
}
var backward = currCount <= lastCount;
if (currCount <= 0) currCount = 1;
if (giftCountCache.ContainsKey(key))
{
lastCount = giftCountCache[key].Item1;
backward = currCount <= lastCount;
if (!backward)
{
lock (giftCountCache)
{
giftCountCache[key] = Tuple.Create(currCount, DateTime.Now);
}
}
}
2024-03-10 03:44:13 +08:00
else
{
2024-03-10 03:44:13 +08:00
if (msg.groupId > 0 && !backward)
{
2024-03-10 03:44:13 +08:00
giftCountCache.TryAdd(key, Tuple.Create(currCount, DateTime.Now));
}
}
2024-03-10 03:44:13 +08:00
//比上次小,则说明先后顺序出了问题,直接丢掉,应为比它大的消息已经处理过了
if (backward) return;
}
2023-03-09 00:33:03 +08:00
var count = currCount - lastCount;
var enty = new GiftMsg()
{
MsgId = msg.Common.msgId,
RoomId = msg.Common.roomId,
WebRoomId = AppRuntime.RoomCaches.GetCachedWebRoomid(msg.Common.roomId.ToString()),
2024-03-10 03:44:13 +08:00
Content = $"{msg.User.Nickname} 送出 {msg.Gift.Name}{(msg.Gift.Combo ? "(可连击)" : "")} x {msg.repeatCount}个,增量{count}个",
DiamondCount = msg.Gift.diamondCount,
2024-03-10 03:44:13 +08:00
RepeatCount = msg.repeatCount,
GiftCount = count,
GroupId = msg.groupId,
GiftId = msg.giftId,
GiftName = msg.Gift.Name,
2024-03-10 03:44:13 +08:00
Combo = msg.Gift.Combo,
2024-03-29 11:20:17 +08:00
ImgUrl = msg.Gift.Image?.urlLists?.FirstOrDefault() ?? "",
User = GetUser(msg.User),
2023-12-17 23:56:10 +08:00
ToUser = GetUser(msg.toUser)
};
2023-11-14 20:29:18 +08:00
2023-12-17 23:56:10 +08:00
if (enty.ToUser != null)
{
enty.Content += ",给" + enty.ToUser.Nickname;
}
var msgType = PackMsgType.礼物消息;
2024-03-29 11:20:17 +08:00
FirePack(enty, msgType);
PrintMsg(enty, msgType);
var pack = new BarrageMsgPack(enty.ToJson(), PackMsgType.礼物消息, e.Process);
Broadcast(pack);
2022-10-06 17:44:08 +08:00
}
2023-03-09 00:33:03 +08:00
//关注
private void Grab_OnSocialMessage(object sender, WssBarrageGrab.RoomMessageEventArgs<SocialMessage> e)
2022-10-06 17:44:08 +08:00
{
var msg = e.Message;
if (!CheckRoomId(msg.Common.roomId)) return;
if (msg.Action != 1) return;
2022-10-06 17:44:08 +08:00
var enty = new Msg()
{
MsgId = msg.Common.msgId,
Content = $"{msg.User.Nickname} 关注了主播",
RoomId = msg.Common.roomId,
WebRoomId = AppRuntime.RoomCaches.GetCachedWebRoomid(msg.Common.roomId.ToString()),
User = GetUser(msg.User)
};
2023-11-14 20:29:18 +08:00
var msgType = PackMsgType.关注消息;
2024-03-29 11:20:17 +08:00
FirePack(enty, msgType);
PrintMsg(enty, msgType);
var pack = new BarrageMsgPack(enty.ToJson(), msgType, e.Process);
2022-10-06 17:44:08 +08:00
var json = JsonConvert.SerializeObject(pack);
Broadcast(pack);
2022-10-06 17:44:08 +08:00
}
//直播间分享
private void Grab_OnShardMessage(object sender, WssBarrageGrab.RoomMessageEventArgs<SocialMessage> e)
{
var msg = e.Message;
if (!CheckRoomId(msg.Common.roomId)) return;
if (msg.Action != 3) return;
ShareType type = ShareType.未知;
if (Enum.IsDefined(type.GetType(), int.Parse(msg.shareTarget)))
{
type = (ShareType)int.Parse(msg.shareTarget);
}
var enty = new ShareMessage()
{
MsgId = msg.Common.msgId,
Content = $"{msg.User.Nickname} 分享了直播间到{type}",
RoomId = msg.Common.roomId,
WebRoomId = AppRuntime.RoomCaches.GetCachedWebRoomid(msg.Common.roomId.ToString()),
ShareType = type,
User = GetUser(msg.User)
};
2023-11-14 20:29:18 +08:00
var msgType = PackMsgType.直播间分享;
2024-03-29 11:20:17 +08:00
FirePack(enty, msgType);
PrintMsg(enty, msgType);
//shareTarget: (112:好友),(1微信)(2朋友圈)(3微博)(5:qq)(4:qq空间),shareType: 1
var pack = new BarrageMsgPack(enty.ToJson(), msgType, e.Process);
var json = JsonConvert.SerializeObject(pack);
Broadcast(pack);
}
2023-03-09 00:33:03 +08:00
//来了
private void Grab_OnMemberMessage(object sender, WssBarrageGrab.RoomMessageEventArgs<Modles.ProtoEntity.MemberMessage> e)
2022-10-06 17:44:08 +08:00
{
var msg = e.Message;
if (!CheckRoomId(msg.Common.roomId)) return;
2023-08-17 20:37:22 +08:00
var enty = new Modles.JsonEntity.MemberMessage()
2022-10-06 17:44:08 +08:00
{
MsgId = msg.Common.msgId,
Content = $"{msg.User.Nickname} 来了 直播间人数:{msg.memberCount}",
RoomId = msg.Common.roomId,
WebRoomId = AppRuntime.RoomCaches.GetCachedWebRoomid(msg.Common.roomId.ToString()),
CurrentCount = msg.memberCount,
User = GetUser(msg.User)
2022-10-06 17:44:08 +08:00
};
2023-11-14 20:29:18 +08:00
var msgType = PackMsgType.进直播间;
2024-03-29 11:20:17 +08:00
FirePack(enty, msgType);
PrintMsg(enty, msgType);
var pack = new BarrageMsgPack(enty.ToJson(), msgType, e.Process);
2022-10-06 17:44:08 +08:00
var json = JsonConvert.SerializeObject(pack);
Broadcast(pack);
2022-10-06 17:44:08 +08:00
}
2023-03-09 00:33:03 +08:00
//点赞
private void Grab_OnLikeMessage(object sender, WssBarrageGrab.RoomMessageEventArgs<LikeMessage> e)
2022-10-06 17:44:08 +08:00
{
var msg = e.Message;
if (!CheckRoomId(msg.Common.roomId)) return;
2022-10-06 17:44:08 +08:00
var enty = new LikeMsg()
{
MsgId = msg.Common.msgId,
Count = msg.Count,
Content = $"{msg.User.Nickname} 为主播点了{msg.Count}个赞,总点赞{msg.Total}",
RoomId = msg.Common.roomId,
WebRoomId = AppRuntime.RoomCaches.GetCachedWebRoomid(msg.Common.roomId.ToString()),
Total = msg.Total,
User = GetUser(msg.User)
2022-10-06 17:44:08 +08:00
};
2023-11-14 20:29:18 +08:00
var msgType = PackMsgType.点赞消息;
2024-03-29 11:20:17 +08:00
FirePack(enty, msgType);
PrintMsg(enty, msgType);
var pack = new BarrageMsgPack(enty.ToJson(), msgType, e.Process);
Broadcast(pack);
2022-10-06 17:44:08 +08:00
}
2023-03-09 00:33:03 +08:00
//弹幕
private void Grab_OnChatMessage(object sender, WssBarrageGrab.RoomMessageEventArgs<ChatMessage> e)
2022-10-06 17:44:08 +08:00
{
var msg = e.Message;
if (!CheckRoomId(msg.Common.roomId)) return;
2022-10-06 17:44:08 +08:00
var enty = new Msg()
{
MsgId = msg.Common.msgId,
Content = msg.Content,
RoomId = msg.Common.roomId,
WebRoomId = AppRuntime.RoomCaches.GetCachedWebRoomid(msg.Common.roomId.ToString()),
User = GetUser(msg.User),
2022-10-06 17:44:08 +08:00
};
2023-11-14 20:29:18 +08:00
var msgType = PackMsgType.弹幕消息;
2024-03-29 11:20:17 +08:00
FirePack(enty, msgType);
PrintMsg(enty, msgType);
2023-04-24 21:39:22 +08:00
var pack = new BarrageMsgPack(enty.ToJson(), msgType, e.Process);
Broadcast(pack);
2022-10-06 17:44:08 +08:00
}
//直播间状态变更
private void Grab_OnControlMessage(object sender, WssBarrageGrab.RoomMessageEventArgs<ControlMessage> e)
{
var msg = e.Message;
if (!CheckRoomId(msg.Common.roomId)) return;
BarrageMsgPack pack = null;
//下播
if (msg.Status == 3)
{
var enty = new Msg()
{
MsgId = msg.Common.msgId,
Content = "直播已结束",
RoomId = msg.Common.roomId,
WebRoomId = AppRuntime.RoomCaches.GetCachedWebRoomid(msg.Common.roomId.ToString()),
User = null
};
2023-11-14 20:29:18 +08:00
var msgType = PackMsgType.下播;
2024-03-29 11:20:17 +08:00
FirePack(enty, msgType);
PrintMsg(enty, msgType);
pack = new BarrageMsgPack(enty.ToJson(), PackMsgType.下播, e.Process);
}
if (pack != null)
{
Broadcast(pack);
}
}
2024-03-29 11:20:17 +08:00
//监听用户连接
2022-10-06 17:44:08 +08:00
private void Listen(IWebSocketConnection socket)
{
//客户端url
string clientUrl = socket.ConnectionInfo.ClientIpAddress + ":" + socket.ConnectionInfo.ClientPort;
if (!socketList.ContainsKey(clientUrl))
{
socketList.Add(clientUrl, new UserState(socket));
2024-03-10 03:44:13 +08:00
Logger.PrintColor($"{DateTime.Now.ToLongTimeString()} 已经建立与[{clientUrl}]的连接", ConsoleColor.Green);
2022-10-06 17:44:08 +08:00
}
else
{
socketList[clientUrl].Socket = socket;
}
2023-06-19 21:44:21 +08:00
//接收指令
socket.OnMessage = (message) =>
{
try
{
var cmdPack = JsonConvert.DeserializeObject<Command>(message);
if (cmdPack == null) return;
2023-11-14 20:29:18 +08:00
switch (cmdPack.Cmd)
2023-06-19 21:44:21 +08:00
{
2023-11-14 20:29:18 +08:00
case CommandCode.Close:
this.Close();
break;
case CommandCode.EnableProxy:
{
var enable = (bool)cmdPack.Data;
if (enable)
this.grab.Proxy.RegisterSystemProxy();
else
this.grab.Proxy.CloseSystemProxy();
break;
}
case CommandCode.DisplayConsole:
{
var display = (bool)cmdPack.Data;
2023-12-17 23:56:10 +08:00
AppRuntime.DisplayConsole(display);
2023-11-14 20:29:18 +08:00
break;
}
2023-06-19 21:44:21 +08:00
}
}
2023-08-17 20:37:22 +08:00
catch (Exception) { }
2023-06-19 21:44:21 +08:00
};
2022-10-06 17:44:08 +08:00
socket.OnClose = () =>
{
socketList.Remove(clientUrl);
2024-03-10 03:44:13 +08:00
Logger.PrintColor($"{DateTime.Now.ToLongTimeString()} 已经关闭与[{clientUrl}]的连接", ConsoleColor.Red);
2022-10-06 17:44:08 +08:00
};
socket.OnPing = (data) =>
{
socketList[clientUrl].LastPing = DateTime.Now;
socket.SendPong(Encoding.UTF8.GetBytes("pong"));
};
}
/// <summary>
/// 广播消息
/// </summary>
/// <param name="msg"></param>
public void Broadcast(BarrageMsgPack pack)
2022-10-06 17:44:08 +08:00
{
if (pack == null) return;
2023-11-23 16:43:21 +08:00
if (Appsetting.Current.PushFilter.Any() && !Appsetting.Current.PushFilter.Contains(pack.Type.GetHashCode())) return;
var offLines = new List<string>();
foreach (var item in socketList)
2022-10-06 17:44:08 +08:00
{
var state = item.Value;
if (item.Value.Socket.IsAvailable)
2023-11-14 20:29:18 +08:00
{
state.Socket.Send(pack.ToJson());
}
else
{
offLines.Add(item.Key);
}
2022-10-06 17:44:08 +08:00
}
//删除掉线的套接字
offLines.ForEach(key => socketList.Remove(key));
2022-10-06 17:44:08 +08:00
}
2023-03-09 00:33:03 +08:00
/// <summary>
/// 开始监听
/// </summary>
2022-10-06 17:44:08 +08:00
public void StartListen()
{
this.grab.Start(); //启动代理
2023-11-16 09:26:40 +08:00
this.socketServer.Start(Listen);//启动监听
2022-10-06 17:44:08 +08:00
}
/// <summary>
2023-06-19 21:44:21 +08:00
/// 关闭服务器连接,并关闭系统代理
2022-10-06 17:44:08 +08:00
/// </summary>
public void Close()
{
socketList.Values.ToList().ForEach(f => f.Socket.Close());
socketList.Clear();
socketServer.Dispose();
grab.Dispose();
2023-08-17 20:37:22 +08:00
this.OnClose?.Invoke(this, EventArgs.Empty);
2022-10-06 17:44:08 +08:00
}
2024-03-29 11:20:17 +08:00
/// <summary>
/// 客户端套接字上下文
/// </summary>
2022-10-06 17:44:08 +08:00
class UserState
{
/// <summary>
/// 套接字
/// </summary>
public IWebSocketConnection Socket { get; set; }
/// <summary>
/// 上次发起心跳包时间
/// </summary>
public DateTime LastPing { get; set; } = DateTime.Now;
public UserState()
{
}
public UserState(IWebSocketConnection socket)
{
Socket = socket;
}
}
2023-11-23 16:43:21 +08:00
2024-03-29 11:20:17 +08:00
/// <summary>
/// Print事件参数
/// </summary>
2023-11-23 16:43:21 +08:00
public class PrintEventArgs : EventArgs
{
public string Message { get; set; }
2023-12-17 23:56:10 +08:00
public ConsoleColor Color { get; set; }
2023-11-23 16:43:21 +08:00
public PackMsgType MsgType { get; set; }
}
2024-03-29 11:20:17 +08:00
/// <summary>
/// 消息包事件参数
/// </summary>
public class PackMsgEventArgs
{
/// <summary>
/// 消息类型
/// </summary>
public PackMsgType MsgType { get; set; }
/// <summary>
/// 消息内容
/// </summary>
public Msg Message { get; set; }
}
2022-10-06 17:44:08 +08:00
}
}