powerfun-new-net/ViewModels/MainWindowViewModel.cs

1026 lines
38 KiB
C#
Raw Normal View History

2020-10-13 08:54:24 +08:00
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using OnlineUserPool.Hander;
using OnlineUserPool.Model;
using OnlineUserPool.Unility;
using Serilog;
using System.Linq;
using System.Net;
using System.Windows.Threading;
using System.Diagnostics;
using OnlineUserPool.Services;
using Newtonsoft.Json;
using System.Collections.Concurrent;
2021-12-24 18:35:21 +08:00
using System.Windows;
2022-05-10 19:23:32 +08:00
using OnlineUserPool.Api;
2020-10-13 08:54:24 +08:00
namespace OnlineUserPool.ViewModels
{
public class MainWindowViewModel : BindableBase
2022-05-10 19:23:32 +08:00
{
2020-10-13 08:54:24 +08:00
public ObservableCollection<HostModel> Clients { get; private set; } = new ObservableCollection<HostModel>();
private static ConcurrentBag<MsgModel> receiveMes = new ConcurrentBag<MsgModel>();
2022-05-10 19:23:32 +08:00
private static CustomList<RoomModel> RoomList = new CustomList<RoomModel>();
2022-05-18 10:39:35 +08:00
private static int RoomMaxId = 0;
private static int Ticks = 0;
2020-10-13 08:54:24 +08:00
private static object locker = new object();
public static System.Timers.Timer timer;
private static IHandle mapRecordRankingHander;
2020-10-13 08:54:24 +08:00
private Dispatcher dispatcher;
2024-01-24 15:23:28 +08:00
public ObservableCollection<MsgModel> Customers { get; private set; } = new ObservableCollection<MsgModel>();
2020-10-27 10:20:47 +08:00
private string _Title = "";
public string Title
{
get { return _Title; }
set
{
SetProperty(ref _Title, value);
}
}
2020-10-13 08:54:24 +08:00
private string _SendDataSize = "";
public string SendDataSize
{
get { return _SendDataSize; }
set
{
SetProperty(ref _SendDataSize, value);
}
}
2021-12-24 18:35:21 +08:00
private string _VirtualData = "";
public string VirtualData
{
get { return _VirtualData; }
set
{
SetProperty(ref _VirtualData, value);
}
}
private bool _closeVirtualUser = false;
public bool CloseVirtualUser
{
get { return _closeVirtualUser; }
set
{
SetProperty(ref _closeVirtualUser, value);
}
}
2024-01-24 15:23:28 +08:00
private const int ROOM_TIME_OUT = 60;
private const int TOTAL_PROCESS = 100;
//private IService _udpService;
2021-12-24 18:35:21 +08:00
2020-10-13 08:54:24 +08:00
public MainWindowViewModel()
{
2022-05-10 19:23:32 +08:00
//初始化对战房间信息
var r = GameRoomHelper.Get();
foreach (var item in r)
{
RoomList.Add(item);
}
2022-05-18 10:39:35 +08:00
RoomMaxId = GameRoomHelper.GetMaxId();
2022-05-10 19:23:32 +08:00
//初测程序关闭事件
Application.Current.MainWindow.Closing += MainWindow_Closing;
2021-06-24 09:20:01 +08:00
Title = $"{ IPAddress.Any }:{ ConfigHelp.UdpPort }";
2020-10-13 08:54:24 +08:00
dispatcher = Dispatcher.CurrentDispatcher;
WriteLine(DateTime.Now.ToShortDateString());
LogHelper.Init();
2021-12-24 18:35:21 +08:00
mapRecordRankingHander = new MapRecordRankingHander();//
2021-06-24 09:20:01 +08:00
//mapRecordRankingHander = new MultiUserHandle();
Log.Information($"初始化连接,当前地址:{ IPAddress.Any }:{ConfigHelp.UdpPort}");
2024-01-24 15:23:28 +08:00
new TcpService().RunServer(ReceivedData, ClientDisconnected);
var _udpService = new UdpService();
_udpService.RunServer(ReceivedData);
2020-10-13 08:54:24 +08:00
Log.Information("服务启动成功");
timer = new System.Timers.Timer(500);
2020-10-13 08:54:24 +08:00
timer.Elapsed += Timer_Elapsed;
timer.AutoReset = true;
timer.Start();
Log.Information("等待连接");
2024-01-24 15:23:28 +08:00
ReleaseMemory();
}
private void ReleaseMemory()
{
var timers = new System.Timers.Timer(3333);
timers.Elapsed += (s, e) =>
{
GC.Collect();
};
timers.AutoReset = true;
timers.Start();
2020-10-13 08:54:24 +08:00
}
2022-05-10 19:23:32 +08:00
private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
GameRoomHelper.Set(RoomList.ToList());
2022-05-18 10:39:35 +08:00
GameRoomHelper.SetMaxId(RoomMaxId);
2022-05-10 19:23:32 +08:00
}
2021-07-07 09:49:36 +08:00
private void ReceivedData(IPEndPoint remoteIpEndPoint, ReceiveModel msg, IService service)
2020-10-13 08:54:24 +08:00
{
dispatcher.Invoke(() =>
2020-10-13 08:54:24 +08:00
{
if (!Clients.Any(c => c.Equals(remoteIpEndPoint)))
2020-10-13 08:54:24 +08:00
{
2024-01-08 10:44:46 +08:00
if (msg is SetClientCommand client)
2020-10-13 08:54:24 +08:00
{
2024-01-08 10:44:46 +08:00
Clients.Add(new HostModel
{
IPEndPoint = remoteIpEndPoint,
LastActiveTime = DateTime.Now,
Service = service,
MemberId = client.MemberId,
Encoding = client.Encoding,
V = client.V
});
}
}
2020-10-13 08:54:24 +08:00
2021-07-07 09:49:36 +08:00
switch (msg.CommandType)
{
//ping命令
case 0:
{
var client = Clients.FirstOrDefault(n => n.Equals(remoteIpEndPoint));
client.LastActiveTime = DateTime.Now;
2022-05-10 19:23:32 +08:00
if (msg.V > 0)
2021-07-07 09:49:36 +08:00
{
client.V = msg.V;
}
}
break;
//消息
case 1:
{
var client = Clients.FirstOrDefault(n => n.Equals(remoteIpEndPoint));
var msg1 = (msg as MsgModel);
2024-01-24 15:23:28 +08:00
client.Competitionid = msg1.CompetitionId;
2022-05-10 19:23:32 +08:00
client.Model = msg1.Model;
2024-01-24 15:23:28 +08:00
2022-05-18 10:39:35 +08:00
if (client.Model == "")
{
client.RoomId = msg1.RoomId;
}
2024-01-24 15:23:28 +08:00
2021-07-07 09:49:36 +08:00
if (msg1.V > 0)
{
client.V = msg1.V;
}
2024-01-24 15:23:28 +08:00
2021-07-07 09:49:36 +08:00
receiveMes.Add(msg1);
2022-05-18 10:39:35 +08:00
HandleGameRoomSaved(msg1);
2021-07-07 09:49:36 +08:00
}
break;
//设置客户端
case 2:
{
var client = Clients.FirstOrDefault(n => n.Equals(remoteIpEndPoint));
var msg1 = (msg as SetClientCommand);
client.Encoding = msg1.Encoding;
client.Client = msg1.Client;
client.V = msg1.V;
client.MemberId = msg1.MemberId;
client.Competitionid = msg1.Competitionid;
client.IsWatch = msg1.IsWatch;
}
break;
2022-05-10 19:23:32 +08:00
//GameRoom
case 3:
{
HandleGameRoom(msg);
}
break;
2020-10-13 08:54:24 +08:00
}
});
}
private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
2022-05-18 10:39:35 +08:00
Ticks++;
NotifyClient();
2022-05-18 10:39:35 +08:00
//定时保存当前房间信息
if (Ticks % 5 == 0)
{
GameRoomHelper.SetMaxId(RoomMaxId);
GameRoomHelper.Set(RoomList.ToList());
}
}
2024-01-24 15:23:28 +08:00
2022-05-18 10:39:35 +08:00
private void HandleGameRoomSaved(MsgModel msg1)
{
//对战房间内的人保存处理
if (msg1.RoomId > 0 && msg1.Saved)
{
2024-01-08 10:44:46 +08:00
var current = RoomList.ToList().FirstOrDefault(c => c.RoomId == msg1.RoomId);
2022-05-18 10:39:35 +08:00
if (current != null)
{
//更新房间内的人的保存状态
2024-01-08 10:44:46 +08:00
var currentPlayer = current.List.FirstOrDefault(c => c.UserId == msg1.MemberId);
2022-05-18 10:39:35 +08:00
if (currentPlayer != null)
{
currentPlayer.Saved = true;
}
2024-01-08 10:44:46 +08:00
var notAllSaved = current.List.Any(c => !c.Saved);
2022-05-18 10:39:35 +08:00
if (!notAllSaved && current.Status != 2)
{
current.Status = 2;
WebService.UpdateGameRoom(current.RoomId, current.Status);
}
if (!current.Saved)
{
2024-01-08 10:44:46 +08:00
notAllSaved = current.List.Any(c => !c.Saved);
2022-05-18 10:39:35 +08:00
if (!notAllSaved && current.Status != 2)
{
current.Status = 2;
}
current.Saved = true;
WebService.AddGameRoom(current.RoomId, current.Status, current.UserId, current.Name, current.MapRouteId, current.Password, current.StartTime.Value, current.CloseTime, current.MaxMembers);
}
}
}
}
2022-05-10 19:23:32 +08:00
private void HandleGameRoom(ReceiveModel msg)
{
//收
switch (msg.SubType)
{
case 0: HandleCreateGameRoom(msg); break;
case 1: HandleJoinGameRoom(msg); break;
case 2: HandleGameRoomReadyStatus(msg); break;
case 3: HandleGameRoomStart(msg); break;
case 4: HandleGameRoomKick(msg); break;
case 5: HandleGameRoomProcess(msg); break;
case 6: HandleQueryGameRoomList(msg); break;//查询房间列表
default:
break;
}
switch (msg.SubType)
{
case 0:
case 1:
case 2:
case 3:
case 4: BroadCastGameRoomList(); break;
}
}
2022-05-10 19:23:32 +08:00
private void SendGameRoomMessage(RoomModel gameRoom)
{
if (gameRoom == null)
return;
var list = new List<MsgModel>();
list.Add(new MsgModel()
{
V = 2,
Point = new double[] { 0d, 0d },
});
string ss = "";
if (gameRoom.List != null && gameRoom.List.Count > 0)
{
ss = string.Join("|", gameRoom.List.Select(c => c.ToString()));
}
2022-05-18 10:39:35 +08:00
int total = 0;
var G = $"{total}l[{gameRoom},detail{{{ss}}}]";
2022-05-10 19:23:32 +08:00
var temp = string.Join("|", list.Select(m => m.ToString(2))) + "|";
var strV21 = $"*l{{{ temp }}};g{{{ G}}};#";
2023-08-01 10:55:45 +08:00
var ddd = new NetworkData(strV21);
2022-05-10 19:23:32 +08:00
var needList = Clients.Where(c => c.RoomId == gameRoom.RoomId).ToList();
foreach (var client in needList)
{
bool isZip = client.Encoding == "gzip";
client.Service.Send(ddd.GetBytes(isZip), ddd.GetBytes(isZip).Length, client.IPEndPoint);
client.Request = "";
}
}
2022-05-10 19:23:32 +08:00
private void BroadCastGameRoomList()
{
//广播
2022-05-18 10:39:35 +08:00
var needlist = Clients.Where(c => c.Model != null && c.Model.Equals("GameRoom") && !string.IsNullOrEmpty(c.Request));
2022-05-10 19:23:32 +08:00
var list = new List<MsgModel>();
list.Add(new MsgModel()
{
V = 2,
Point = new double[] { 0d, 0d },
});
var temp = string.Join("|", list.Select(m => m.ToString(2))) + "|";
foreach (var item in needlist)
{
var G = GameRoomMessageHandler(item);
2022-05-18 10:39:35 +08:00
var strV21 = $"*l{{{ temp }}};g{{{G}}};#";
2023-08-01 10:55:45 +08:00
var ddd = new NetworkData(strV21);
2022-05-10 19:23:32 +08:00
bool isZip = item.Encoding == "gzip";
item.Service.Send(ddd.GetBytes(isZip), ddd.GetBytes(isZip).Length, item.IPEndPoint);
}
}
2022-05-10 19:23:32 +08:00
//查询房间列表
private void HandleQueryGameRoomList(ReceiveModel msg)
{
var query = msg as QueryGameRoomListCommand;
var needSend = Clients.Where(c => c.MemberId == query.UserId).FirstOrDefault();
if (needSend == null)
return;
needSend.Request = $"List/{query.PageIndex}/{query.PageSize}/{query.Name}";
var list = new List<MsgModel>();
list.Add(new MsgModel()
{
V = 2,
Point = new double[] { 0d, 0d },
});
2024-01-24 15:23:28 +08:00
var temp = string.Join("|", list.Where(m => m.CompetitionId == needSend.Competitionid).Select(m => m.ToString(2))) + "|";
2022-05-10 19:23:32 +08:00
List<RoomModel> rooms;
if (!string.IsNullOrEmpty(query.Name))
{
2022-05-18 10:39:35 +08:00
rooms = RoomList.ToList().Where(c => c.Name.Contains(query.Name) || c.RoomId.ToString() == query.Name).OrderBy(c => c.Status).ThenByDescending(c => c.CreateTime).ToList();
2022-05-10 19:23:32 +08:00
}
else
{
2022-05-18 10:39:35 +08:00
rooms = RoomList.ToList().OrderBy(c => c.Status).ThenByDescending(c => c.CreateTime).ToList();
2022-05-10 19:23:32 +08:00
}
2022-05-18 10:39:35 +08:00
//计算总页数
int total = 0;
if (query.PageSize != 0)
{
total = rooms.Count() / query.PageSize;
total = rooms.Count() % query.PageSize == 0 ? total : total + 1;
}
rooms = rooms.Skip(query.PageIndex * query.PageSize).Take(query.PageSize).ToList();
string roomInfo = $"{total}l";
2022-05-10 19:23:32 +08:00
foreach (var r in rooms)
{
string ss = "";
if (r.List != null && r.List.Count > 0)
{
ss = string.Join("|", r.List.Select(c => c.ToString()));
}
2022-05-18 10:39:35 +08:00
roomInfo += $"[{r.ToString()},detail{{{ss}}}]";
2022-05-10 19:23:32 +08:00
}
2022-05-18 10:39:35 +08:00
var strV21 = $"*l{{{ temp }}};g{{{roomInfo}}};#";
2023-08-01 10:55:45 +08:00
var ddd = new NetworkData(strV21);
2022-05-10 19:23:32 +08:00
bool isZip = needSend.Encoding == "gzip";
needSend.Service.Send(ddd.GetBytes(isZip), ddd.GetBytes(isZip).Length, needSend.IPEndPoint);
}
2022-05-10 19:23:32 +08:00
//创建房间
private void HandleCreateGameRoom(ReceiveModel msg)
{
var createMsg = msg as CreateGameRoomCommand;
2023-02-10 09:43:04 +08:00
RemoveOtherRoomInfo(createMsg.UserId, createMsg.Id);
var roomId = RoomMaxId + 1;
2022-05-10 19:23:32 +08:00
var list = new List<RoomDetailModel>();
list.Add(new RoomDetailModel()
{
2023-02-10 09:43:04 +08:00
RoomId = roomId,
2022-05-10 19:23:32 +08:00
UserId = createMsg.UserId,
JoinAt = DateTime.Now.ToUniversalTime(),
IsOwner = true,
});
2023-02-10 09:43:04 +08:00
2022-05-10 19:23:32 +08:00
var room = new RoomModel
{
2022-05-18 10:39:35 +08:00
RoomId = roomId,
2022-05-10 19:23:32 +08:00
Name = createMsg.Name,
Password = createMsg.Password,
CloseTime = createMsg.CloseTime,
CreateTime = createMsg.CreateTime,
MapRouteId = createMsg.RouteId,
MapRouteName = createMsg.MapRouteName,
AltitudeGraph = createMsg.AltitudeGraph,
MaxMembers = createMsg.MaxMembers,
UserId = createMsg.UserId,
AverageGrade = createMsg.AverageGrade,
TotalClimb = createMsg.TotalClimb,
Distance = createMsg.Distance,
EnableAR = createMsg.EnableAR,
Enable3D = createMsg.Enable3D,
FileName = createMsg.FileName,
FileUrl = createMsg.FileUrl,
IsLock = !string.IsNullOrEmpty(createMsg.Password),
List = list,
};
2024-01-08 10:44:46 +08:00
var mine = Clients.FirstOrDefault(c => c.MemberId == createMsg.UserId);
2022-05-10 19:23:32 +08:00
if (mine != null)
{
mine.RoomId = room.RoomId;
}
RoomList.Add(room);
2022-05-18 10:39:35 +08:00
RoomMaxId = room.RoomId;
}
2022-05-18 10:39:35 +08:00
//先移除当前用户在其他房间的信息(考虑服务器重启的时候没有响应客户端退出命令)
2023-02-10 09:43:04 +08:00
private void RemoveOtherRoomInfo(int userId, int roomId)
2022-05-18 10:39:35 +08:00
{
var preRoom = RoomList.ToList().FirstOrDefault(c => c.Status == 0 && c.List.Any(a => a.UserId == userId) && c.RoomId != roomId);
2022-05-18 10:39:35 +08:00
if (preRoom != null)
{
var needRemove = preRoom.List.FirstOrDefault(c => c.UserId == userId && c.Saved == false);
2022-05-18 10:39:35 +08:00
preRoom.List.Remove(needRemove);
if (preRoom.List.Count == 0)
{
RoomList.Remove(preRoom);
}
//发送给这个房间的人
SendGameRoomMessage(preRoom);
}
2022-05-10 19:23:32 +08:00
}
2022-05-10 19:23:32 +08:00
//处理当前用户加入房间
private void HandleJoinGameRoom(ReceiveModel msg)
{
var msg1 = msg as JoinGameRoomCommand;
2023-02-10 09:43:04 +08:00
RemoveOtherRoomInfo(msg1.UserId,msg1.RoomId);
2024-01-08 10:44:46 +08:00
var room = RoomList.ToList().FirstOrDefault(c => c.RoomId == msg1.RoomId);
2022-05-10 19:23:32 +08:00
var client = Clients.FirstOrDefault(n => n.MemberId.Equals(msg1.UserId));
//更新房间信息
if (room != null)
{
var list = room.List;
2024-01-08 10:44:46 +08:00
var member = list.FirstOrDefault(c => c.UserId == msg1.UserId);
2022-05-10 19:23:32 +08:00
if (member != null)
{
member.JoinAt = msg1.JoinAt;
}
else
{
2022-05-18 10:39:35 +08:00
//如果房间人数已经满了就拒绝加入
var currentCount = room.List.Count;
if (currentCount + 1 <= room.MaxMembers)
2022-05-10 19:23:32 +08:00
{
2022-05-18 10:39:35 +08:00
list.Add(new RoomDetailModel
{
UserId = msg1.UserId,
JoinAt = msg1.JoinAt,
RoomId = msg1.RoomId
});
if (client != null)
{
client.RoomId = room.RoomId;
client.Request = "";
}
}
2022-05-10 19:23:32 +08:00
}
}
//发送当前房间的信息给当前房间内的人
SendGameRoomMessage(room);
}
2022-05-10 19:23:32 +08:00
//处理当前用户准备状态
private void HandleGameRoomReadyStatus(ReceiveModel msg)
{
var msg1 = msg as GameRoomReadyCommand;
var room = RoomList.ToList().Where(c => c.RoomId == msg1.RoomId).FirstOrDefault();
if (room != null)
{
var list = room.List;
var member = list.Where(c => c.UserId == msg1.UserId).FirstOrDefault();
if (member != null)
{
member.Status = msg1.Status;
}
}
//发送信息给当前房间内的人
SendGameRoomMessage(room);
}
2022-05-10 19:23:32 +08:00
//处理当前用户准备状态
private void HandleGameRoomStart(ReceiveModel msg)
{
var msg1 = msg as GameRoomStartCommand;
2024-01-08 10:44:46 +08:00
var client = Clients.FirstOrDefault(c => c.MemberId == msg1.UserId);
2022-05-18 10:39:35 +08:00
if (client != null)
{
client.RoomId = msg1.RoomId;
}
2024-01-08 10:44:46 +08:00
var room = RoomList.ToList().FirstOrDefault(c => c.RoomId == msg1.RoomId);
2022-05-10 19:23:32 +08:00
if (room != null)
{
room.Status = 1;
room.StatusChangedTime = DateTime.Now;
}
//发送信息给当前房间内的人
SendGameRoomMessage(room);
}
2022-05-10 19:23:32 +08:00
//处理房间踢人的操作
private void HandleGameRoomKick(ReceiveModel msg)
{
var msg1 = msg as GameRoomKickCommand;
var room = RoomList.ToList().FirstOrDefault(c => c.RoomId == msg1.RoomId);
if (room != null && room.Status !=2)
2022-05-10 19:23:32 +08:00
{
var list = room.List;
var needRemove = list.FirstOrDefault(c => c.UserId == msg1.UserId);
2022-05-10 19:23:32 +08:00
if (needRemove != null)
{
list.Remove(needRemove);
//如果当前是房主退出房间,房主替换成其他人, 房主客户端中断也算
if (needRemove.IsOwner && list.Any())
2022-05-10 19:23:32 +08:00
{
var newOwner = list.FirstOrDefault();
newOwner.IsOwner = true;
room.UserId = newOwner.UserId;
}
}
//房间没有产生记录且人数为0删除房间
if (!room.Saved && !list.Any())
2022-05-10 19:23:32 +08:00
{
RoomList.Remove(room);
}
var mine = Clients.FirstOrDefault(c => c.MemberId == msg1.UserId);
2022-05-10 19:23:32 +08:00
if (mine != null)
{
mine.RoomId = 0;
}
//发送信息给当前房间内的人
SendGameRoomMessage(room);
}
}
2024-01-24 15:23:28 +08:00
2022-05-10 19:23:32 +08:00
//处理房间内人loading进度
private void HandleGameRoomProcess(ReceiveModel msg)
{
var msg1 = msg as GameRoomProcessCommand;
var room = RoomList.ToList().Where(c => c.RoomId == msg1.RoomId).FirstOrDefault();
var client = Clients.Where(c => c.MemberId == msg1.UserId).FirstOrDefault();
if (room != null)
{
var list = room.List;
var player = list.Where(c => c.UserId == msg1.UserId).FirstOrDefault();
if (player != null)
{
player.Process = msg1.Process;
}
var notReady = list.Where(c => c.Process < TOTAL_PROCESS).Any();
var now = DateTime.Now;
var timespan = now - room.StatusChangedTime;
//超时时间1分钟所有人强制开始
if ((notReady && timespan.TotalSeconds > ROOM_TIME_OUT) || !notReady)
{
room.StartTime = now.AddSeconds(10).ToUniversalTime();
}
if (client != null)
{
client.RoomId = room.RoomId;
}
SendGameRoomMessage(room);
}
}
private string GameRoomMessageHandler(HostModel item)
{
//如果当前Client有请求房间列表信息发送房间列表信息
var G = "";
if (!string.IsNullOrEmpty(item.Request))
{
var param = item.Request.Split('/');
var pageInfo = param[0];
if (pageInfo.Equals("List"))
{
var pageIndex = Convert.ToInt32(param[1]);
var pageSize = Convert.ToInt32(param[2]);
var querName = param[3].ToString();
List<RoomModel> rooms;
2022-05-18 10:39:35 +08:00
2022-05-10 19:23:32 +08:00
if (!string.IsNullOrEmpty(querName))
{
2022-05-18 10:39:35 +08:00
rooms = RoomList.ToList().Where(c => c.Name.Contains(querName) || c.RoomId.ToString() == querName).OrderBy(c => c.Status).ThenByDescending(c => c.CreateTime).ToList();
2022-05-10 19:23:32 +08:00
}
else
{
2022-05-18 10:39:35 +08:00
rooms = RoomList.ToList().OrderBy(c => c.Status).ThenByDescending(c => c.CreateTime).ToList();
}
//计算总页数
int total = 0;
if (pageSize != 0)
{
total = rooms.Count() / pageSize;
total = rooms.Count() % pageSize == 0 ? total : total + 1;
2022-05-10 19:23:32 +08:00
}
2022-05-18 10:39:35 +08:00
G = $"{total}l";
rooms = rooms.Skip(pageIndex * pageSize).Take(pageSize).ToList();
2022-05-10 19:23:32 +08:00
foreach (var r in rooms)
{
string ss = "";
if (r.List != null && r.List.Count > 0)
{
ss = string.Join("|", r.List.Select(c => c.ToString()));
}
G += $"[{r.ToString()},detail{{{ss}}}]";
}
}
}
2022-05-18 10:39:35 +08:00
return G;
2022-05-10 19:23:32 +08:00
}
2020-10-13 08:54:24 +08:00
private void NotifyClient()
{
try
{
2022-05-10 19:23:32 +08:00
if (!receiveMes.Any())
2021-06-24 09:20:01 +08:00
{
dispatcher.Invoke(() =>
{
//移除5钟内连接不上的客户端
Clients.ToList().ForEach(item =>
{
if (item.Expire)
{
RemoveClient(item);
2021-06-24 09:20:01 +08:00
}
});
});
return;
}
2024-01-24 15:23:28 +08:00
2020-10-13 08:54:24 +08:00
lock (locker)
{
dispatcher.Invoke(() =>
{
2024-01-24 15:23:28 +08:00
var msgs = receiveMes.ToList();
//加入虚拟人物消息
if (!CloseVirtualUser)
2020-10-13 08:54:24 +08:00
{
2024-01-24 15:23:28 +08:00
var virtualData = mapRecordRankingHander.GetVirtualUserData();
VirtualData = $"{virtualData.Count}";
msgs.AddRange(virtualData);
2020-10-13 08:54:24 +08:00
}
2024-01-24 15:23:28 +08:00
//屏蔽房间模式的用户
var c = Clients.Where(c => string.IsNullOrEmpty(c.Model)).ToList();
SendMessage(c, msgs);
RemoveClientAdvanced(msgs);
AddCustomers(msgs);
receiveMes.Clear();
msgs.Clear();
msgs = null;
2020-10-13 08:54:24 +08:00
});
2024-01-24 15:23:28 +08:00
//更新虚拟人物信息
mapRecordRankingHander.RemoveEndAndAddNewVirtualUser(Clients.Count);
2020-10-13 08:54:24 +08:00
}
}
catch (Exception e)
{
2020-10-27 10:20:47 +08:00
Log.Error($"NotifyClient:{ e.Message }\r\n{ e.StackTrace }");
2020-10-13 08:54:24 +08:00
}
}
2024-01-24 15:23:28 +08:00
private void RemoveClientAdvanced(List<MsgModel> msgs)
2020-10-13 08:54:24 +08:00
{
2024-01-24 15:23:28 +08:00
//移除下线的客户端
for (int i = 0; i < msgs.Count; i++)
{
if (msgs[i].Exit && msgs[i].MemberId > 0)//客户端退出,并且不是虚拟的人物
{
//这个地方有严重的逻辑错误(虚拟的人物不能和真实的人用同一个名字)
var info = Clients.FirstOrDefault(n => n.MemberId == msgs[i].MemberId);
if (info != null)
{
RemoveClient(info);
}
}
}
//移除5钟内连接不上的客户端
Clients.ToList().ForEach(item =>
{
if (item.Expire)
{
RemoveClient(item);
}
});
}
private void AddCustomers(List<MsgModel> msgs)
{
foreach (var item in msgs)
{
var client = Clients.FirstOrDefault(c => c.MemberId == item.MemberId);
if (client == null)
{
Customers.Remove(item);
continue;
}
var customer = Customers.FirstOrDefault(c => c.MemberId == item.MemberId);
if (customer != null)
{
customer.Update(item);
}
else
{
Customers.Add(item);
}
}
}
private StringBuilder sb = new StringBuilder();
private void SendMessage(IList<HostModel> clients, List<MsgModel> list)
{
if (!clients.Any() || !list.Any())
2021-06-24 09:20:01 +08:00
{
return;
}
2024-01-24 15:23:28 +08:00
var clients1 = clients.ToList();
foreach (var item in list)
{
item.PreDistance = Math.Round(item.PreDistance, 5);
item.EndDistance = Math.Round(item.EndDistance, 5);
item.WeightKg = Math.Round(item.WeightKg, 2);
}
2021-07-07 09:49:36 +08:00
#region
foreach (var item in clients1)
2020-10-13 08:54:24 +08:00
{
try
{
2023-08-01 10:55:45 +08:00
if (item == null) continue;
2021-07-07 09:49:36 +08:00
if (item.V != 1 && item.V != 2)
2021-06-24 09:20:01 +08:00
{
2024-01-24 15:23:28 +08:00
var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(list.Select(m => new {
m.RouteId,
m.MemberId,
m.Point,
m.IsCompleted,
exit = m.Exit,
m.Speed,
m.PreDistance,
m.EndDistance,
//m.IsVirtual,//后面要把这个字段过滤掉
m.WeightKg,
Competitionid = m.CompetitionId,
m.Saved,
m.FrameRate,
}));
var data = Encoding.ASCII.GetBytes(jsonString);
2021-07-07 09:49:36 +08:00
item.Service.Send(data, data.Length, item.IPEndPoint);
2024-01-24 15:23:28 +08:00
data = null;
2021-06-24 09:20:01 +08:00
continue;
}
2023-08-01 10:55:45 +08:00
2021-07-07 09:49:36 +08:00
if (item.V == 1 && item.Service is UdpService)
2021-06-24 09:20:01 +08:00
{
2024-01-24 15:23:28 +08:00
sb.Clear();
foreach (var obj in list)
{
sb.Append(obj.ToString(1));
sb.Append("|");
}
var strV1 = sb.ToString();
var data1ForUdp = new NetworkData(strV1.Last() == '|' ? strV1.Substring(0, strV1.Length - 1) : strV1);
2021-07-07 09:49:36 +08:00
item.Service.Send(data1ForUdp.GetBytes(), data1ForUdp.GetBytes().Length, item.IPEndPoint);
2024-01-24 15:23:28 +08:00
data1ForUdp = null;
}
2023-08-01 10:55:45 +08:00
if(item.Service is TcpService)
{
2024-01-24 15:23:28 +08:00
NetworkData networkData = null;
2021-07-07 09:49:36 +08:00
if (item.V == 1)
{
2024-01-24 15:23:28 +08:00
sb.Clear();
foreach (var obj in list)
{
sb.Append(obj.ToString(1));
sb.Append("|");
}
var strV1 = sb.ToString();
var data1 = new NetworkData(strV1);
networkData = data1;
2021-07-07 09:49:36 +08:00
}
else if (item.V == 2)
{
2024-01-24 15:23:28 +08:00
networkData = HandleGzipNetworkData(list,item);
2021-07-07 09:49:36 +08:00
}
else
{
continue;
}
2024-01-24 15:23:28 +08:00
2021-07-07 09:49:36 +08:00
bool isZip = item.Encoding == "gzip";
2024-01-24 15:23:28 +08:00
item.Service.Send(networkData.GetBytes(isZip), networkData.GetBytes(isZip).Length, item.IPEndPoint);
networkData = null;
2022-05-10 19:23:32 +08:00
}
2020-10-13 08:54:24 +08:00
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
Log.Error($"{ item.IPEndPoint.ToString() }:{ e.Message }\r\n{ e.StackTrace }");
2020-10-13 08:54:24 +08:00
}
}
2024-01-24 15:23:28 +08:00
clients1 = null;
2021-07-07 09:49:36 +08:00
#endregion
2020-10-13 08:54:24 +08:00
}
2024-01-24 15:23:28 +08:00
private NetworkData HandleGzipNetworkData(List<MsgModel> list, HostModel item)
{
sb.Clear();
foreach (var obj in list.Where(m => m.CompetitionId == item.Competitionid).Select(m => m.ToString(2)))
{
sb.Append(obj);
sb.Append("|");
}
sb.Remove(sb.Length - 1, 1);
var temp = sb.ToString();
sb.Clear();
foreach (var obj in Clients.Where(c => c.IsWatch && c.Competitionid == item.Competitionid).Select(c => c.MemberId))
{
sb.Append(obj);
sb.Append("|");
}
if (sb.Length > 0)
{
sb.Remove(sb.Length - 1, 1);
}
var watchList1 = sb.ToString();
sb.Clear();
foreach (var c in list.Where(c => c.RoomId > 0 || c.FrameRate > 0))
{
sb.Append($"{c.MemberId},{c.RoomId},{c.FrameRate},{c.TotalTicks}");
sb.Append("|");
}
if (sb.Length > 0)
{
sb.Remove(sb.Length - 1, 1);
}
var e = sb.ToString();
sb.Clear();
sb.Append("*l{");
sb.Append(temp);
sb.Append("};w{");
sb.Append(watchList1);
sb.Append("};e{");
sb.Append(e);
sb.Append("};#");
var strV2 = sb.ToString();
var data2 = new NetworkData(strV2);
return data2;
}
2022-05-10 19:23:32 +08:00
private void GameRoomDisConnectHandler(HostModel client)
{
////如果是在对战房间或者对战列表掉线执行,骑行阶段断开连接不移除房间信息
//if (client.Model != null && !client.Model.Equals("GameRoom"))
// return;
2022-05-10 19:23:32 +08:00
RoomList.ToList().ForEach(o => {
if (o.List != null && o.Status != 2)
2022-05-10 19:23:32 +08:00
{
var needRemove = o.List.FirstOrDefault(c => c.UserId == client.MemberId && c.Saved == false);
2022-05-10 19:23:32 +08:00
o.List.Remove(needRemove);
}
});
2024-01-24 15:23:28 +08:00
var needRemoveList = RoomList.ToList().Where(c => c.List.Count == 0 && c.Status != 2).ToList();
2022-05-10 19:23:32 +08:00
foreach (var item in needRemoveList)
{
RoomList.Remove(item);
}
2024-01-24 15:23:28 +08:00
2022-05-10 19:23:32 +08:00
BroadCastGameRoomList();
}
2020-10-13 08:54:24 +08:00
void WriteLine(string str)
{
//Debug.WriteLine(str);
}
T CloneJson<T>(T source)
{
// Don't serialize a null object, simply return the default for that object
if (Object.ReferenceEquals(source, null))
{
return default(T);
}
// initialize inner objects individually
// for example in default constructor some list property initialized with some values,
// but in 'source' these items are cleaned -
// without ObjectCreationHandling.Replace default constructor values will be added to result
var deserializeSettings = new JsonSerializerSettings { ObjectCreationHandling = ObjectCreationHandling.Replace };
return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(source), deserializeSettings);
2020-10-13 08:54:24 +08:00
}
2021-07-07 09:49:36 +08:00
2024-01-24 15:23:28 +08:00
private void ClientDisconnected(EndPoint point)
{
dispatcher.Invoke(() =>
2021-07-07 09:49:36 +08:00
{
try
2021-07-07 09:49:36 +08:00
{
var client = Clients.FirstOrDefault(f => f.IPEndPoint.ToString() == point.ToString());
if (client != null)
{
RemoveClient(client);
2022-05-10 19:23:32 +08:00
GameRoomDisConnectHandler(client);
}
}
catch(Exception ex)
{
2024-01-24 15:23:28 +08:00
Log.Information("在ClientDisconnected触发以后删除client时报错了,"+ ex.Message +", " + ex.StackTrace);
}
});
2021-07-07 09:49:36 +08:00
}
private void RemoveClient(HostModel client)
{
BeforeRemoved(client);
Clients.Remove(client);
2024-01-24 15:23:28 +08:00
Customers.Clear();
}
2021-07-07 09:49:36 +08:00
private void BeforeRemoved(HostModel client)
{
if(client.RoomId == 0)return;
var room = RoomList.ToList().FirstOrDefault(c => c.RoomId == client.RoomId);
if(room == null)return;
var needRemove = room.List.FirstOrDefault(c => c.UserId == client.MemberId && c.Saved == false);
if(needRemove == null)return;
//从房间中移除,并考虑是否需要删除房间和移交房主
room.List.Remove(needRemove);
if (room.List.Count == 0)
{
RoomList.Remove(room);
}
else
{
var host = room.List.FirstOrDefault();
if (host != null)
{
host.IsOwner = true;
}
}
//更新房间状态
var isComplete = room.List.All(c => c.Saved != false);
if (room.Status > 0)
{
room.Status = isComplete ? 2 : 1;
}
}
}
2023-08-01 10:55:45 +08:00
public class NetworkData
2021-07-07 09:49:36 +08:00
{
private string _txt = "";
2023-08-01 10:55:45 +08:00
public NetworkData(string txt)
2021-07-07 09:49:36 +08:00
{
this._txt = txt;
}
public byte[] GetBytes(bool compress = false)
{
if (compress)
{
return GetCompressBytes();
}
return Encoding.UTF8.GetBytes(this._txt);
}
private byte[] GetCompressBytes()
{
var temp = this._txt;
if(temp[0] == '*')
{
temp = temp.Substring(1);
}
if(temp.Last() == '#')
{
temp = temp.Substring(0, temp.Length - 1);
}
return Encoding.UTF8.GetBytes($"*{ Convert.ToBase64String(CommonHelper.Compress(temp)) }#");
}
2020-10-13 08:54:24 +08:00
}
}