封装Socket,添加心跳检测

This commit is contained in:
Mili 2022-08-25 00:16:10 +08:00
parent 38b2ca9b33
commit b71bd4e9fa
5 changed files with 160 additions and 25 deletions

View File

@ -9,7 +9,6 @@
<ItemGroup> <ItemGroup>
<Folder Include="Models\Entity\" /> <Folder Include="Models\Entity\" />
<Folder Include="Models\Config\" />
</ItemGroup> </ItemGroup>
</Project> </Project>

48
Main.cs
View File

@ -5,27 +5,27 @@ using System.Text.RegularExpressions;
using System; using System;
using FunGameServer.Sockets; using FunGameServer.Sockets;
using System.Net.WebSockets; using System.Net.WebSockets;
using FunGameServer.Models.Config;
bool Running = true; bool Running = true;
Socket? ServerSocket = null; Socket? ServerSocket = null;
string host = "127.0.0.1"; string host = Config.SERVER_IPADRESS;
int port = 22222; int port = Config.SERVER_PORT;
try try
{ {
Task t = Task.Factory.StartNew(() => Task t = Task.Factory.StartNew(() =>
{ {
// 创建IP地址终结点对象 // 创建IP地址终结点对象
IPAddress ip = IPAddress.Parse(host); IPEndPoint ip = new(IPAddress.Parse(host), port);
IPEndPoint ipe = new IPEndPoint(ip, port);
// 创建TCP Socket对象并绑定终结点 // 创建TCP Socket对象并绑定终结点
ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
ServerSocket.Bind(ipe); ServerSocket.Bind(ip);
// 开始监听连接 // 开始监听连接
ServerSocket.Listen(0); ServerSocket.Listen(Config.MAX_PLAYERS);
Console.WriteLine("服务器启动成功,正在监听 . . ."); Console.WriteLine("服务器启动成功,正在监听 . . .");
while (Running) while (Running)
@ -39,14 +39,16 @@ try
Console.WriteLine("客户端" + clientIP.ToString() + "连接 . . ."); Console.WriteLine("客户端" + clientIP.ToString() + "连接 . . .");
else else
Console.WriteLine("未知地点客户端连接 . . ."); Console.WriteLine("未知地点客户端连接 . . .");
Task.Factory.StartNew(() => if (Read(socket) && Send(socket))
{ Task.Factory.StartNew(() =>
new ClientSocket(socket, Running).Start(); {
}); new ClientSocket(socket, Running).Start();
// 接收客户端消息 });
Read(socket); else
// 发送给客户端消息 if (clientIP != null)
Send(socket); Console.WriteLine("客户端" + clientIP.ToString() + "连接失败。");
else
Console.WriteLine("客户端连接失败。");
} }
catch (Exception e) catch (Exception e)
{ {
@ -87,7 +89,7 @@ Console.WriteLine("服务器已关闭,按任意键退出程序。");
Console.ReadKey(); Console.ReadKey();
void Read(Socket socket) bool Read(Socket socket)
{ {
// 接收客户端消息 // 接收客户端消息
byte[] buffer = new byte[2048]; byte[] buffer = new byte[2048];
@ -95,20 +97,28 @@ void Read(Socket socket)
if (length > 0) if (length > 0)
{ {
string msg = Encoding.GetEncoding("unicode").GetString(buffer, 0, length); string msg = Encoding.GetEncoding("unicode").GetString(buffer, 0, length);
Console.WriteLine("收到来自:客户端 -> " + msg); Console.WriteLine("收到来自客户端玩家ID -> " + msg);
return true;
} }
else else
Console.WriteLine("客户端没有回应。"); Console.WriteLine("客户端没有回应。");
return false;
} }
void Send(Socket socket) bool Send(Socket socket)
{ {
// 发送消息给客户端 // 发送消息给客户端
string msg = ">> 已连接至服务器 -> [ " + host + " ] 连接成功"; string msg = ">> 已连接至服务器 -> [ " + host + " ] 连接成功";
Console.WriteLine("发送给:客户端 <- " + msg);
byte[] buffer = new byte[2048]; byte[] buffer = new byte[2048];
buffer = Encoding.GetEncoding("unicode").GetBytes(msg); buffer = Encoding.GetEncoding("unicode").GetBytes(msg);
socket.Send(buffer); if (socket.Send(buffer) > 0)
{
Console.WriteLine("发送给:客户端 <- " + msg);
return true;
}
else
Console.WriteLine("无法传输数据,与客户端的连接可能丢失。");
return false;
} }
bool IsIP(string ip) bool IsIP(string ip)

34
Models/Config/Config.cs Normal file
View File

@ -0,0 +1,34 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Reflection.Metadata;
using System.Text;
using System.Threading.Tasks;
namespace FunGameServer.Models.Config
{
public static class Config
{
public static int MAX_PLAYERS = 16; // 最多接受连接的玩家数量
public static int ONLINE_PLAYERS = 0; // 已连接的玩家数量
public static int CONNECTING_PLAYERS = 0; // 正在连接的玩家数量
public static string SERVER_IPADRESS = "127.0.0.1"; // 默认IP地址
public static int SERVER_PORT = 22222; // 默认端口
/// <summary>
/// string: 玩家标识ID
/// Task玩家线程
/// </summary>
public static ConcurrentDictionary<string, Task> OnlinePlayers = new ConcurrentDictionary<string, Task>();
/**
* string
* stringID
* Task线
*/
public static ConcurrentDictionary<string, ConcurrentDictionary<string, Task>> PlayingPlayers= new ConcurrentDictionary<string, ConcurrentDictionary<string, Task>>();
}
}

View File

@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FunGameServer.Models.Config
{
public static class SocketEnums
{
public enum SendType
{
Login = 1,
CheckLogin = 2,
Logout = 3,
HeartBeat = 4,
}
public enum ReadType
{
Login = 1,
CheckLogin = 2,
Logout = 3,
HeartBeat = 4,
}
}
}

View File

@ -1,6 +1,8 @@
using System; using FunGameServer.Models.Config;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.IO;
using System.Net.Sockets; using System.Net.Sockets;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
@ -18,6 +20,59 @@ namespace FunGameServer.Sockets
Running = running; Running = running;
} }
bool Read(Socket socket)
{
// 接收客户端消息
byte[] buffer = new byte[2048];
int length = socket.Receive(buffer);
if (length > 0)
{
string type = Encoding.GetEncoding("unicode").GetString(buffer, 0, length);
Console.Write("收到来自:客户端(" + type + " -> ");
buffer = new byte[2048];
length = socket.Receive(buffer);
if (length > 0)
{
string msg = Encoding.GetEncoding("unicode").GetString(buffer, 0, length);
Console.WriteLine(msg);
int getType = Convert.ToInt32(type);
if (getType == (int)SocketEnums.ReadType.HeartBeat) // 检测心跳包
Send(socket, getType, msg);
return true;
}
else
Console.WriteLine("客户端没有回应。");
return false;
}
else
Console.WriteLine("客户端没有回应。");
return false;
}
bool Send(Socket socket, int type, string msg)
{
// 发送消息给客户端
byte[] buffer = new byte[2048];
buffer = Encoding.GetEncoding("unicode").GetBytes(Convert.ToString(type));
if (socket.Send(buffer) > 0)
{
Console.Write("发送给:客户端(" + type + " <- ");
buffer = new byte[2048];
buffer = Encoding.GetEncoding("unicode").GetBytes(msg);
if (socket.Send(buffer) > 0)
{
Console.WriteLine("发送给:客户端(" + msg + " <- ");
return true;
}
else
Console.WriteLine("无法传输数据,与客户端的连接可能丢失。");
return false;
}
else
Console.WriteLine("无法传输数据,与客户端的连接可能丢失。");
return false;
}
public void Start() public void Start()
{ {
Task StringStream = Task.Factory.StartNew(() => Task StringStream = Task.Factory.StartNew(() =>
@ -44,7 +99,14 @@ namespace FunGameServer.Sockets
Console.WriteLine("Creating: StringStream...OK"); Console.WriteLine("Creating: StringStream...OK");
while (Running) while (Running)
{ {
if (Socket != null)
Read(Socket);
else
{
Console.WriteLine("ERROR: Socket is Closed.");
Console.WriteLine("DONE: StringStream is Closed.");
break;
}
} }
} }
@ -54,7 +116,8 @@ namespace FunGameServer.Sockets
Console.WriteLine("Creating: IntStream...OK"); Console.WriteLine("Creating: IntStream...OK");
while (Running) while (Running)
{ {
Console.WriteLine("DONE: IntStream is Closed.");
break;
} }
} }
@ -64,7 +127,8 @@ namespace FunGameServer.Sockets
Console.WriteLine("Creating: DecimalStream...OK"); Console.WriteLine("Creating: DecimalStream...OK");
while (Running) while (Running)
{ {
Console.WriteLine("DONE: DecimalStream is Closed.");
break;
} }
} }
@ -74,7 +138,8 @@ namespace FunGameServer.Sockets
Console.WriteLine("Creating: ObjectStream...OK"); Console.WriteLine("Creating: ObjectStream...OK");
while (Running) while (Running)
{ {
Console.WriteLine("DONE: ObjectStream is Closed.");
break;
} }
} }
} }