添加一些工具方法

This commit is contained in:
风吹落的叶子 2022-11-12 23:37:01 +08:00
parent 154df1dc7a
commit 173a7a8169
3 changed files with 147 additions and 62 deletions

View File

@ -1,6 +1,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Net.NetworkInformation;
using System.Reflection; using System.Reflection;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Text; using System.Text;
@ -8,12 +9,15 @@ using System.Text.RegularExpressions;
using System.Threading.Tasks; using System.Threading.Tasks;
using Milimoe.FunGame.Core.Entity.Enum; using Milimoe.FunGame.Core.Entity.Enum;
// 通用工具类,客户端和服务器端都可以直接调用的工具方法都可以写在这里
namespace Milimoe.FunGame.Core.Api.Utility namespace Milimoe.FunGame.Core.Api.Utility
{ {
#region
/// <summary> /// <summary>
/// 通用工具类,客户端和服务器端都可以直接调用的工具方法都可以写在这里 /// 网络服务工具箱
/// </summary> /// </summary>
public class Utility public class NetworkUtility
{ {
/// <summary> /// <summary>
/// 判断字符串是否是IP地址 /// 判断字符串是否是IP地址
@ -77,5 +81,115 @@ namespace Milimoe.FunGame.Core.Api.Utility
else if (IsIP(ip) && (port <= 0 || port >= 65536)) return ErrorType.IsNotPort; else if (IsIP(ip) && (port <= 0 || port >= 65536)) return ErrorType.IsNotPort;
else return ErrorType.WrongFormat; else return ErrorType.WrongFormat;
} }
/// <summary>
/// 获取服务器的延迟
/// </summary>
/// <param name="addr">服务器IP地址</param>
/// <returns></returns>
public static int GetServerPing(string addr)
{
Ping pingSender = new();
PingOptions options = new()
{
DontFragment = true
};
string data = "getserverping";
byte[] buffer = Encoding.ASCII.GetBytes(data);
int timeout = 120;
PingReply reply = pingSender.Send(addr, timeout, buffer, options);
if (reply.Status == IPStatus.Success)
{
return Convert.ToInt32(reply.RoundtripTime);
}
return -1;
} }
} }
#endregion
#region
/// <summary>
/// 时间服务工具箱
/// </summary>
public class DateTimeUtility
{
/// <summary>
/// 获取系统时间
/// </summary>
/// <param name="type">格式化类型</param>
/// <returns></returns>
public static DateTime GetDateTime(TimeType type)
{
DateTime now = DateTime.Now;
if (type == TimeType.DateOnly)
return now.Date;
else return now;
}
/// <summary>
/// 通过字符串转换为DateTime对象
/// </summary>
/// <param name="format">时间字符串</param>
/// <returns>转换失败返回当前时间</returns>
public static DateTime GetDateTime(string format)
{
DateTime dt = default;
if (DateTime.TryParse(format, out dt))
{
return dt;
}
else
{
return DateTime.Now;
}
}
/// <summary>
/// 获取系统时间并转为字符串
/// </summary>
/// <param name="type">格式化类型</param>
/// <returns></returns>
public static string GetDateTimeToString(TimeType type)
{
DateTime now = DateTime.Now;
return type switch
{
TimeType.General => now.ToString("yyyy-MM-dd HH:mm:ss"),
TimeType.DateOnly => now.Date.ToString(""),
TimeType.TimeOnly => now.ToString("T"),
TimeType.Year4 => now.Year.ToString(),
TimeType.Year2 => "'" + now.ToString("yy"),
TimeType.Month => now.Month.ToString(),
TimeType.Day => now.Day.ToString(),
TimeType.Hour => now.Hour.ToString(),
TimeType.Minute => now.Minute.ToString(),
TimeType.Second => now.Second.ToString(),
_ => now.ToString("yyyy-MM-dd HH:mm:ss")
};
}
/// <summary>
/// 获取系统短日期
/// </summary>
/// <returns></returns>
public static string GetNowShortTime()
{
DateTime now = DateTime.Now;
return now.AddMilliseconds(-now.Millisecond).ToString("T");
}
/// <summary>
/// 获取系统日期
/// </summary>
/// <returns></returns>
public static string GetNowTime()
{
DateTime now = DateTime.Now;
return now.AddMilliseconds(-now.Millisecond).ToString();
}
}
#endregion
}

View File

@ -103,4 +103,18 @@ namespace Milimoe.FunGame.Core.Entity.Enum
Character, Character,
CharacterStatistics CharacterStatistics
} }
public enum TimeType
{
General,
DateOnly,
TimeOnly,
Year4,
Year2,
Month,
Day,
Hour,
Minute,
Second
}
} }

View File

@ -96,7 +96,7 @@ namespace Milimoe.FunGame.Desktop.UI
Others.Config.FunGame_isRetrying = false; Others.Config.FunGame_isRetrying = false;
SocketHelper_Action = (main) => SocketHelper_Action = (main) =>
{ {
SetServerStatusLight((int)LightType.Green, ping: GetServerPing(Others.Constant.SERVER_IPADRESS)); SetServerStatusLight((int)LightType.Green, ping: NetworkUtility.GetServerPing(Others.Constant.SERVER_IPADRESS));
SetButtonEnableIfLogon(true, ClientState.Online); SetButtonEnableIfLogon(true, ClientState.Online);
}; };
if (InvokeRequired) if (InvokeRequired)
@ -186,13 +186,13 @@ namespace Milimoe.FunGame.Desktop.UI
if (Others.Config.FunGame_isAutoRetry) Connect(); // 再次判断是否开启自动重连 if (Others.Config.FunGame_isAutoRetry) Connect(); // 再次判断是否开启自动重连
}); });
if (needTime) if (needTime)
throw new Exception(GetNowShortTime() + "\nERROR连接服务器失败5秒后自动尝试重连。"); throw new Exception(DateTimeUtility.GetNowShortTime() + "\nERROR连接服务器失败5秒后自动尝试重连。");
else else
throw new Exception("ERROR连接服务器失败5秒后自动尝试重连。"); throw new Exception("ERROR连接服务器失败5秒后自动尝试重连。");
} }
else else
if (needTime) if (needTime)
throw new Exception(GetNowShortTime() + "\nERROR无法连接至服务器请检查你的网络连接。"); throw new Exception(DateTimeUtility.GetNowShortTime() + "\nERROR无法连接至服务器请检查你的网络连接。");
else else
throw new Exception("ERROR无法连接至服务器请检查你的网络连接。"); throw new Exception("ERROR无法连接至服务器请检查你的网络连接。");
case Others.Constant.SocketHelper_Disconnect: case Others.Constant.SocketHelper_Disconnect:
@ -266,7 +266,7 @@ namespace Milimoe.FunGame.Desktop.UI
return null; return null;
default: default:
if (needTime) if (needTime)
WritelnGameInfo(SocketHelper, GetNowShortTime() + msg); WritelnGameInfo(SocketHelper, DateTimeUtility.GetNowShortTime() + msg);
else else
WritelnGameInfo(SocketHelper, msg); WritelnGameInfo(SocketHelper, msg);
return null; return null;
@ -340,9 +340,9 @@ namespace Milimoe.FunGame.Desktop.UI
{ {
NOW_CONNECTEDRETRY++; NOW_CONNECTEDRETRY++;
if (NOW_CONNECTEDRETRY == 0) if (NOW_CONNECTEDRETRY == 0)
WritelnGameInfo(GetNowTime() + " >> 开始连接服务器..."); WritelnGameInfo(DateTimeUtility.GetNowTime() + " >> 开始连接服务器...");
else else
WritelnGameInfo(GetNowTime() + " >> 第" + NOW_CONNECTEDRETRY + "次重试连接服务器..."); WritelnGameInfo(DateTimeUtility.GetNowTime() + " >> 第" + NOW_CONNECTEDRETRY + "次重试连接服务器...");
if (NOW_CONNECTEDRETRY + 1 > MAX_CONNECTEDRETRY) // 判断重连次数是否达到上限 if (NOW_CONNECTEDRETRY + 1 > MAX_CONNECTEDRETRY) // 判断重连次数是否达到上限
{ {
WritelnGameInfo("ERROR无法连接至服务器请检查网络并重启游戏再试。"); WritelnGameInfo("ERROR无法连接至服务器请检查网络并重启游戏再试。");
@ -421,7 +421,7 @@ namespace Milimoe.FunGame.Desktop.UI
} }
catch (Exception e) catch (Exception e)
{ {
WritelnGameInfo(GetNowTime() + e.Message != null ? e.Message + "\n" + e.StackTrace : "" + e.StackTrace); WritelnGameInfo(DateTimeUtility.GetNowTime() + e.Message != null ? e.Message + "\n" + e.StackTrace : "" + e.StackTrace);
} }
} }
@ -434,7 +434,7 @@ namespace Milimoe.FunGame.Desktop.UI
Others.Config.FunGame_Roomid = roomid; Others.Config.FunGame_Roomid = roomid;
if (!roomid.Equals("-1")) if (!roomid.Equals("-1"))
{ {
WritelnGameInfo(GetNowShortTime() + " 加入房间"); WritelnGameInfo(DateTimeUtility.GetNowShortTime() + " 加入房间");
WritelnGameInfo("[ " + Usercfg.LoginUserName + " ] 已加入房间 -> [ " + Others.Config.FunGame_Roomid + " ]"); WritelnGameInfo("[ " + Usercfg.LoginUserName + " ] 已加入房间 -> [ " + Others.Config.FunGame_Roomid + " ]");
Room.Text = "[ 当前房间 ]\n" + Convert.ToString(Others.Config.FunGame_Roomid); Room.Text = "[ 当前房间 ]\n" + Convert.ToString(Others.Config.FunGame_Roomid);
} }
@ -521,7 +521,7 @@ namespace Milimoe.FunGame.Desktop.UI
{ {
// 显示:匹配、创建房间 // 显示:匹配、创建房间
// 隐藏:退出房间、房间设定 // 隐藏:退出房间、房间设定
WritelnGameInfo(GetNowShortTime() + " 离开房间"); WritelnGameInfo(DateTimeUtility.GetNowShortTime() + " 离开房间");
WritelnGameInfo("[ " + Usercfg.LoginUserName + " ] 已离开房间 -> [ " + Others.Config.FunGame_Roomid + " ]"); WritelnGameInfo("[ " + Usercfg.LoginUserName + " ] 已离开房间 -> [ " + Others.Config.FunGame_Roomid + " ]");
SetRoomid("-1"); SetRoomid("-1");
QuitRoom.Visible = false; QuitRoom.Visible = false;
@ -684,7 +684,7 @@ namespace Milimoe.FunGame.Desktop.UI
if (objs != null) roomid = (string)objs[0]; if (objs != null) roomid = (string)objs[0];
if (!roomid.Equals(-1)) if (!roomid.Equals(-1))
{ {
WritelnGameInfo(GetNowShortTime() + " 匹配成功"); WritelnGameInfo(DateTimeUtility.GetNowShortTime() + " 匹配成功");
WritelnGameInfo(">> 房间号: " + roomid); WritelnGameInfo(">> 房间号: " + roomid);
SetRoomid(roomid); SetRoomid(roomid);
} }
@ -722,7 +722,7 @@ namespace Milimoe.FunGame.Desktop.UI
Login.Enabled = isPause; Login.Enabled = isPause;
break; break;
case (int)StartMatchState.Cancel: case (int)StartMatchState.Cancel:
WritelnGameInfo(GetNowShortTime() + " 终止匹配"); WritelnGameInfo(DateTimeUtility.GetNowShortTime() + " 终止匹配");
WritelnGameInfo("[ " + Usercfg.LoginUserName + " ] 已终止匹配。"); WritelnGameInfo("[ " + Usercfg.LoginUserName + " ] 已终止匹配。");
Others.Config.FunGame_isMatching = false; Others.Config.FunGame_isMatching = false;
StartMatch_Action = (i, objs) => StartMatch_Action = (i, objs) =>
@ -801,7 +801,7 @@ namespace Milimoe.FunGame.Desktop.UI
// 向消息队列发送消息 // 向消息队列发送消息
if (!TalkText.Text.Trim().Equals("") && !TalkText.ForeColor.Equals(Color.DarkGray)) if (!TalkText.Text.Trim().Equals("") && !TalkText.ForeColor.Equals(Color.DarkGray))
{ {
WritelnGameInfo((!Usercfg.LoginUserName.Equals("") ? GetNowShortTime() + " [ " + Usercfg.LoginUserName + " ] 说: ": ":> ") + TalkText.Text); WritelnGameInfo((!Usercfg.LoginUserName.Equals("") ? DateTimeUtility.GetNowShortTime() + " [ " + Usercfg.LoginUserName + " ] 说: ": ":> ") + TalkText.Text);
SwitchTalkMessage(TalkText.Text); SwitchTalkMessage(TalkText.Text);
TalkText.Text = ""; TalkText.Text = "";
if (isLeave) TalkText_Leave(); // 回车不离开焦点 if (isLeave) TalkText_Leave(); // 回车不离开焦点
@ -820,7 +820,7 @@ namespace Milimoe.FunGame.Desktop.UI
/// <param name="msg"></param> /// <param name="msg"></param>
private void SendTalkText_Click(string msg) private void SendTalkText_Click(string msg)
{ {
WritelnGameInfo((!Usercfg.LoginUserName.Equals("") ? GetNowShortTime() + " [ " + Usercfg.LoginUserName + " ] 说: " : ":> ") + msg); WritelnGameInfo((!Usercfg.LoginUserName.Equals("") ? DateTimeUtility.GetNowShortTime() + " [ " + Usercfg.LoginUserName + " ] 说: " : ":> ") + msg);
} }
/// <summary> /// <summary>
@ -873,7 +873,7 @@ namespace Milimoe.FunGame.Desktop.UI
roomid = Convert.ToString(new Random().Next(1, 10000)); roomid = Convert.ToString(new Random().Next(1, 10000));
SetRoomid(roomid); SetRoomid(roomid);
InRoom(); InRoom();
WritelnGameInfo(GetNowShortTime() + " 创建" + roomtype + "房间"); WritelnGameInfo(DateTimeUtility.GetNowShortTime() + " 创建" + roomtype + "房间");
WritelnGameInfo(">> 创建" + roomtype + "房间成功!房间号: " + roomid); WritelnGameInfo(">> 创建" + roomtype + "房间成功!房间号: " + roomid);
ShowMessage.Message("创建" + roomtype + "房间成功!\n房间号是 -> [ " + roomid + " ]", "创建成功"); ShowMessage.Message("创建" + roomtype + "房间成功!\n房间号是 -> [ " + roomid + " ]", "创建成功");
break; break;
@ -984,7 +984,7 @@ namespace Milimoe.FunGame.Desktop.UI
private void StartMatch_Click(object sender, EventArgs e) private void StartMatch_Click(object sender, EventArgs e)
{ {
// 开始匹配 // 开始匹配
WritelnGameInfo(GetNowShortTime() + " 开始匹配"); WritelnGameInfo(DateTimeUtility.GetNowShortTime() + " 开始匹配");
WritelnGameInfo("[ " + Usercfg.LoginUserName + " ] 开始匹配"); WritelnGameInfo("[ " + Usercfg.LoginUserName + " ] 开始匹配");
WriteGameInfo(">> 匹配参数:"); WriteGameInfo(">> 匹配参数:");
if (!Others.Config.Match_Mix && !Others.Config.Match_Team && !Others.Config.Match_HasPass) if (!Others.Config.Match_Mix && !Others.Config.Match_Team && !Others.Config.Match_HasPass)
@ -1411,7 +1411,7 @@ namespace Milimoe.FunGame.Desktop.UI
{ {
SocketHelper.GetSocketHelperMethod((int)SocketHelperMethod.CloseSocket); SocketHelper.GetSocketHelperMethod((int)SocketHelperMethod.CloseSocket);
GetMessage(SocketHelper, Others.Constant.SocketHelper_Disconnect); GetMessage(SocketHelper, Others.Constant.SocketHelper_Disconnect);
WritelnGameInfo(GetNowShortTime() + " >> 你已成功断开与服务器的连接。 "); WritelnGameInfo(DateTimeUtility.GetNowShortTime() + " >> 你已成功断开与服务器的连接。 ");
} }
break; break;
case Others.Constant.FunGame_ConnectTo: case Others.Constant.FunGame_ConnectTo:
@ -1435,7 +1435,7 @@ namespace Milimoe.FunGame.Desktop.UI
ShowMessage.ErrorMessage("格式错误!\n这不是一个服务器地址。"); ShowMessage.ErrorMessage("格式错误!\n这不是一个服务器地址。");
return; return;
} }
ErrorType ErrorType = Utility.IsServerAddress(ip, port); ErrorType ErrorType = NetworkUtility.IsServerAddress(ip, port);
if (ErrorType == Core.Entity.Enum.ErrorType.None) if (ErrorType == Core.Entity.Enum.ErrorType.None)
{ {
Others.Constant.SERVER_IPADRESS = ip; Others.Constant.SERVER_IPADRESS = ip;
@ -1452,49 +1452,6 @@ namespace Milimoe.FunGame.Desktop.UI
} }
} }
/// <summary>
/// 获取系统日期
/// </summary>
/// <returns></returns>
private string GetNowTime()
{
DateTime now = DateTime.Now;
return now.AddMilliseconds(-now.Millisecond).ToString();
}
/// <summary>
/// 获取系统短日期
/// </summary>
/// <returns></returns>
private string GetNowShortTime()
{
DateTime now = DateTime.Now;
return now.AddMilliseconds(-now.Millisecond).ToString("T");
}
/// <summary>
/// 获取服务器的延迟
/// </summary>
/// <param name="addr">服务器IP地址</param>
/// <returns></returns>
private int GetServerPing(string addr)
{
Ping pingSender = new();
PingOptions options = new()
{
DontFragment = true
};
string data = "getserverping";
byte[] buffer = Encoding.ASCII.GetBytes(data);
int timeout = 120;
PingReply reply = pingSender.Send(addr, timeout, buffer, options);
if (reply.Status == IPStatus.Success)
{
return Convert.ToInt32(reply.RoundtripTime);
}
return -1;
}
#endregion #endregion
} }
} }