some network code

This commit is contained in:
2025-02-25 10:11:06 +02:00
parent effd008aa2
commit c6efabe447
9 changed files with 312 additions and 27 deletions

View File

@@ -1,5 +1,7 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\packages\xunit.runner.visualstudio.3.0.2\build\net472\xunit.runner.visualstudio.props" Condition="Exists('..\packages\xunit.runner.visualstudio.3.0.2\build\net472\xunit.runner.visualstudio.props')" />
<Import Project="..\packages\xunit.core.2.9.3\build\xunit.core.props" Condition="Exists('..\packages\xunit.core.2.9.3\build\xunit.core.props')" />
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup> <PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
@@ -13,6 +15,8 @@
<FileAlignment>512</FileAlignment> <FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic> <Deterministic>true</Deterministic>
<TargetFrameworkProfile /> <TargetFrameworkProfile />
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols> <DebugSymbols>true</DebugSymbols>
@@ -35,37 +39,85 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="MelonLoader"> <Reference Include="MelonLoader">
<HintPath>..\..\..\..\AppData\Roaming\r2modmanPlus-local\BONEWORKS\profiles\aaaa\MelonLoader\MelonLoader.dll</HintPath> <HintPath>..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\Stationeers\MelonLoader\MelonLoader.dll</HintPath>
</Reference>
<Reference Include="Microsoft.TestPlatform.CoreUtilities, Version=15.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.TestPlatform.ObjectModel.17.12.0\lib\net462\Microsoft.TestPlatform.CoreUtilities.dll</HintPath>
</Reference>
<Reference Include="Microsoft.TestPlatform.PlatformAbstractions, Version=15.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.TestPlatform.ObjectModel.17.12.0\lib\net462\Microsoft.TestPlatform.PlatformAbstractions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.VisualStudio.TestPlatform.ObjectModel, Version=15.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.TestPlatform.ObjectModel.17.12.0\lib\net462\Microsoft.VisualStudio.TestPlatform.ObjectModel.dll</HintPath>
</Reference> </Reference>
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.Collections.Immutable, Version=1.2.3.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Collections.Immutable.1.5.0\lib\netstandard2.0\System.Collections.Immutable.dll</HintPath>
</Reference>
<Reference Include="System.Configuration" />
<Reference Include="System.Core" /> <Reference Include="System.Core" />
<Reference Include="System.Reflection.Metadata, Version=1.4.3.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Reflection.Metadata.1.6.0\lib\netstandard2.0\System.Reflection.Metadata.dll</HintPath>
</Reference>
<Reference Include="System.Runtime" />
<Reference Include="System.Runtime.Serialization" />
<Reference Include="System.Xml.Linq" /> <Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" /> <Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" /> <Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" /> <Reference Include="System.Data" />
<Reference Include="System.Xml" /> <Reference Include="System.Xml" />
<Reference Include="xunit.abstractions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL">
<HintPath>..\packages\xunit.abstractions.2.0.3\lib\net35\xunit.abstractions.dll</HintPath>
</Reference>
<Reference Include="xunit.assert, Version=2.9.3.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL">
<HintPath>..\packages\xunit.assert.2.9.3\lib\netstandard1.1\xunit.assert.dll</HintPath>
</Reference>
<Reference Include="xunit.core, Version=2.9.3.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL">
<HintPath>..\packages\xunit.extensibility.core.2.9.3\lib\net452\xunit.core.dll</HintPath>
</Reference>
<Reference Include="xunit.execution.desktop, Version=2.9.3.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL">
<HintPath>..\packages\xunit.extensibility.execution.2.9.3\lib\net452\xunit.execution.desktop.dll</HintPath>
</Reference>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Include="MelonLoaderMod.cs" /> <Compile Include="MelonLoaderMod.cs" />
<Compile Include="Networking\LobbyManager\LobbyManager.cs" /> <Compile Include="Networking\LobbyManager\LobbyManager.cs" />
<Compile Include="Networking\LobbyManager\SteamLobbyManager.cs" /> <Compile Include="Networking\LobbyManager\SteamLobbyManager.cs" />
<Compile Include="Networking\Messages\LobbyInfoMessage.cs" />
<Compile Include="Networking\Messages\NetworkMessage.cs" />
<Compile Include="Networking\Packet.cs" /> <Compile Include="Networking\Packet.cs" />
<Compile Include="Networking\PacketTypes.cs" />
<Compile Include="Networking\Transport\SteamTransport.cs" /> <Compile Include="Networking\Transport\SteamTransport.cs" />
<Compile Include="Networking\Transport\TransportBase.cs" /> <Compile Include="Networking\Transport\TransportBase.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Networking\ByteEncoder.cs" /> <Compile Include="Networking\ByteEncoder.cs" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup />
<Folder Include="Networking\Packets\" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="Facepunch.Steamworks\Facepunch.Steamworks.Win64.csproj"> <ProjectReference Include="Facepunch.Steamworks\Facepunch.Steamworks.Win64.csproj">
<Project>{0289f09e-d594-46a9-96a7-b0f31f5d97b0}</Project> <Project>{0289f09e-d594-46a9-96a7-b0f31f5d97b0}</Project>
<Name>Facepunch.Steamworks.Win64</Name> <Name>Facepunch.Steamworks.Win64</Name>
</ProjectReference> </ProjectReference>
</ItemGroup> </ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<Analyzer Include="..\packages\xunit.analyzers.1.18.0\analyzers\dotnet\cs\xunit.analyzers.dll" />
<Analyzer Include="..\packages\xunit.analyzers.1.18.0\analyzers\dotnet\cs\xunit.analyzers.fixes.dll" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<PropertyGroup> <PropertyGroup>
<PostBuildEvent>COPY "$(TargetPath)" "C:\Program Files (x86)\Steam\steamapps\common\BONEWORKS\BONEWORKS\Mods"</PostBuildEvent> <PostBuildEvent>
</PostBuildEvent>
</PropertyGroup> </PropertyGroup>
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\packages\xunit.core.2.9.3\build\xunit.core.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\xunit.core.2.9.3\build\xunit.core.props'))" />
<Error Condition="!Exists('..\packages\xunit.core.2.9.3\build\xunit.core.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\xunit.core.2.9.3\build\xunit.core.targets'))" />
<Error Condition="!Exists('..\packages\xunit.runner.visualstudio.3.0.2\build\net472\xunit.runner.visualstudio.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\xunit.runner.visualstudio.3.0.2\build\net472\xunit.runner.visualstudio.props'))" />
</Target>
<Import Project="..\packages\xunit.core.2.9.3\build\xunit.core.targets" Condition="Exists('..\packages\xunit.core.2.9.3\build\xunit.core.targets')" />
</Project> </Project>

View File

@@ -16,8 +16,8 @@ namespace BoneSync
public class BoneSync : MelonMod public class BoneSync : MelonMod
{ {
LobbyManager lobby; public static LobbyManager lobby;
TransportBase transport; public static TransportBase transport;
public override void OnApplicationStart() public override void OnApplicationStart()
{ {
MelonLogger.Msg("OnApplicationStart"); MelonLogger.Msg("OnApplicationStart");

View File

@@ -9,7 +9,7 @@ using Facepunch.Steamworks.Data;
namespace BoneSync.Networking.LobbyManager namespace BoneSync.Networking.LobbyManager
{ {
internal abstract class LobbyManager public abstract class LobbyManager
{ {
public abstract ulong GetLobbyId(); public abstract ulong GetLobbyId();
public abstract ulong GetHostId(); public abstract ulong GetHostId();

View File

@@ -0,0 +1,62 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace BoneSync.Networking.Messages
{
[PacketType(PacketType.LobbyInfo)]
public class LobbyInfoMessage : NetworkMessage
{
public string LobbyName;
public string HostName;
public int MaxPlayers;
public int CurrentPlayers;
public LobbyInfoMessage(string lobbyName, string hostName, int maxPlayers, int currentPlayers)
{
LobbyName = lobbyName;
HostName = hostName;
MaxPlayers = maxPlayers;
CurrentPlayers = currentPlayers;
byteEncoder.WriteString(LobbyName);
byteEncoder.WriteString(HostName);
byteEncoder.WriteInt(MaxPlayers);
byteEncoder.WriteInt(CurrentPlayers);
}
public LobbyInfoMessage(Packet packet)
{
byteEncoder = new ByteEncoder(packet.Data);
LobbyName = byteEncoder.ReadString();
HostName = byteEncoder.ReadString();
MaxPlayers = byteEncoder.ReadInt();
CurrentPlayers = byteEncoder.ReadInt();
}
public override void Execute()
{
throw new NotImplementedException();
}
}
public class LobbyInfoMessageTests
{
[Fact]
public void TestLobbyInfoMessage()
{
NetworkMessage.RegisterPacketTypes();
LobbyInfoMessage message = new LobbyInfoMessage("TestLobby", "TestHost", 10, 5);
Packet packet = message.GetPacket(0,0,0);
Assert.Equal(PacketType.LobbyInfo, packet.Info.packetType);
LobbyInfoMessage newMessage = (LobbyInfoMessage)NetworkMessage.ParsePacket(packet);
Assert.Equal("TestLobby", newMessage.LobbyName);
Assert.Equal("TestHost", newMessage.HostName);
Assert.Equal(10, newMessage.MaxPlayers);
Assert.Equal(5, newMessage.CurrentPlayers);
}
}
}

View File

@@ -0,0 +1,120 @@
using BoneSync.Networking.Transport;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace BoneSync.Networking.Messages
{
public class PacketTypeAttribute : Attribute
{
public PacketTypeAttribute(PacketType type)
{
packetType = type;
}
public PacketType packetType { get; }
}
public abstract class NetworkMessage
{
private static bool _packetTypesRegistered = false;
internal static Dictionary<PacketType, Type> PacketTypeMap = new Dictionary<PacketType, Type>();
internal PacketType _packetType;
internal ByteEncoder byteEncoder = new ByteEncoder();
public byte[] GetBytes() => byteEncoder.ToArray();
public PacketType GetPacketType()
{
if (_packetType == PacketType.Unknown)
{
Type type = GetType();
_packetType = PacketTypeMap.FirstOrDefault(x => x.Value == type).Key;
if (_packetType == PacketType.Unknown)
{
throw new Exception("Cannot find packetType for " + type.Name);
}
}
return _packetType;
}
public static void RegisterPacketTypes()
{
if (_packetTypesRegistered)
{
return;
}
_packetTypesRegistered = true;
Assembly assembly = Assembly.GetExecutingAssembly();
Type[] types = assembly.GetTypes();
foreach (Type type in types)
{
if (type.IsSubclassOf(typeof(NetworkMessage)))
{
PacketType? packetType = type.GetCustomAttributesData().Where(x => x.AttributeType == typeof(PacketTypeAttribute)).Select(x => (PacketType)x.ConstructorArguments[0].Value).FirstOrDefault();
PacketTypeMap.Add((PacketType)packetType, type);
}
}
}
public static NetworkMessage ParsePacket(Packet packet)
{
// find a class that can parse this packet using Reflection
// and return it
if (!PacketTypeMap.ContainsKey(packet.Info.packetType))
{
throw new Exception("No class found for packet type '" + packet.Info.packetType+"'");
}
Type type = PacketTypeMap[packet.Info.packetType];
// get the constructor that takes a Packet
ConstructorInfo constructor = type.GetConstructor(new Type[] { typeof(Packet) });
// create an instance of the class
if (constructor == null)
{
throw new Exception("No constructor found for type " + type.Name);
}
NetworkMessage networkMessage = (NetworkMessage)constructor.Invoke(new object[] { packet });
return networkMessage;
}
public Packet GetPacket(int id, ulong senderId, ulong receiverId)
{
PacketInfo packetInfo = new PacketInfo(id, senderId, receiverId, GetPacketType());
Packet packet = new Packet(packetInfo, GetBytes());
return packet;
}
public void Broadcast()
{
Send(0);
}
public void Send(ulong receiverId)
{
int PacketId = Packet.GenerateId();
ulong senderId = BoneSync.lobby.GetLocalId();
Packet packet = GetPacket(PacketId, senderId, receiverId);
BoneSync.transport.Send(packet);
}
public abstract void Execute();
}
public class NetworkMessageTests
{
[Fact]
public void TestRegisterPackets()
{
NetworkMessage.RegisterPacketTypes();
Assert.NotEmpty(NetworkMessage.PacketTypeMap);
}
}
}

View File

@@ -3,22 +3,19 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Xunit;
namespace BoneSync.Networking namespace BoneSync.Networking
{ {
public enum PacketType
{ public struct PacketInfo
LobbyInfo = 0,
CharacterInfo = 1,
}
internal struct PacketInfo
{ {
public int id; public int id;
public int senderId; public ulong senderId;
public ulong receiverId; public ulong receiverId;
public PacketType packetType; public PacketType packetType;
public PacketInfo(int id, int senderId, ulong receiverId, PacketType packetType) public PacketInfo(int id, ulong senderId, ulong receiverId, PacketType packetType)
{ {
this.id = id; this.id = id;
this.senderId = senderId; this.senderId = senderId;
@@ -26,30 +23,29 @@ namespace BoneSync.Networking
this.packetType = packetType; this.packetType = packetType;
} }
} }
internal class Packet public class Packet
{ {
public PacketInfo Info public PacketInfo Info
{ {
get => _packetInfo; get => _packetInfo;
private set => _packetInfo = value; private set => _packetInfo = value;
} }
private PacketInfo _packetInfo;
private byte[] dataBytes; private PacketInfo _packetInfo;
private byte[] _dataBytes;
private PacketInfo packetInfo; private PacketInfo packetInfo;
public Packet(PacketInfo packetInfo, byte[] data) public Packet(PacketInfo packetInfo, byte[] data)
{ {
this.packetInfo = packetInfo; _packetInfo = packetInfo;
this.dataBytes = data; _dataBytes = data;
} }
public static Packet FromBytes(byte[] bytes) public static Packet FromBytes(byte[] bytes)
{ {
ByteEncoder byteEncoder = new ByteEncoder(); ByteEncoder byteEncoder = new ByteEncoder();
byteEncoder.WriteBytes(bytes); byteEncoder.WriteBytes(bytes);
PacketInfo packetInfo = new PacketInfo(byteEncoder.ReadInt(), byteEncoder.ReadInt(), byteEncoder.ReadUlong(), (PacketType)byteEncoder.ReadInt()); PacketInfo packetInfo = new PacketInfo(byteEncoder.ReadInt(), byteEncoder.ReadUlong(), byteEncoder.ReadUlong(), (PacketType)byteEncoder.ReadInt());
return new Packet(packetInfo, byteEncoder.ToArray()); return new Packet(packetInfo, byteEncoder.ToArray());
} }
@@ -57,15 +53,41 @@ namespace BoneSync.Networking
{ {
ByteEncoder byteEncoder = new ByteEncoder(); ByteEncoder byteEncoder = new ByteEncoder();
byteEncoder.WriteInt(packetInfo.id); byteEncoder.WriteInt(packetInfo.id);
byteEncoder.WriteInt(packetInfo.senderId); byteEncoder.WriteUlong(packetInfo.senderId);
byteEncoder.WriteUlong(packetInfo.receiverId); byteEncoder.WriteUlong(packetInfo.receiverId);
byteEncoder.WriteInt((int)packetInfo.packetType); byteEncoder.WriteInt((int)packetInfo.packetType);
byteEncoder.WriteBytes(dataBytes); byteEncoder.WriteBytes(_dataBytes);
return byteEncoder.ToArray(); return byteEncoder.ToArray();
} }
public byte[] Data => dataBytes; public byte[] Data => _dataBytes;
public static int GenerateId()
{
return new Random().Next();
}
}
public class PacketTests
{
[Fact]
public void TestPacketParsing()
{
Random random = new Random();
byte[] randomDataBytes = new byte[1024];
random.NextBytes(randomDataBytes);
PacketInfo originalPacketInfo = new PacketInfo(1, 2, 3, PacketType.LobbyInfo);
Packet originalPacket = new Packet(originalPacketInfo, randomDataBytes);
byte[] bytes = originalPacket.ToBytes();
Packet parsedPacket = Packet.FromBytes(bytes);
Assert.Equal(originalPacket.Info, parsedPacket.Info);
Assert.Equal(originalPacket.Data, parsedPacket.Data);
Assert.Equal(randomDataBytes, parsedPacket.Data);
Assert.NotEqual(bytes, randomDataBytes);
}
} }
} }

View File

@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BoneSync.Networking
{
public enum PacketType
{
Unknown = 0,
LobbyInfo = 1,
CharacterInfo = 2,
}
}

View File

@@ -6,7 +6,7 @@ using System.Threading.Tasks;
namespace BoneSync.Networking.Transport namespace BoneSync.Networking.Transport
{ {
internal abstract class TransportBase public abstract class TransportBase
{ {
public abstract void Send(Packet packet); public abstract void Send(Packet packet);
public abstract bool Tick(); public abstract bool Tick();

14
BoneSync/packages.config Normal file
View File

@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Microsoft.TestPlatform.ObjectModel" version="17.12.0" targetFramework="net472" />
<package id="System.Collections.Immutable" version="1.5.0" targetFramework="net472" />
<package id="System.Reflection.Metadata" version="1.6.0" targetFramework="net472" />
<package id="xunit" version="2.9.3" targetFramework="net472" />
<package id="xunit.abstractions" version="2.0.3" targetFramework="net472" />
<package id="xunit.analyzers" version="1.18.0" targetFramework="net472" developmentDependency="true" />
<package id="xunit.assert" version="2.9.3" targetFramework="net472" />
<package id="xunit.core" version="2.9.3" targetFramework="net472" />
<package id="xunit.extensibility.core" version="2.9.3" targetFramework="net472" />
<package id="xunit.extensibility.execution" version="2.9.3" targetFramework="net472" />
<package id="xunit.runner.visualstudio" version="3.0.2" targetFramework="net472" developmentDependency="true" />
</packages>