Skip to content

Commit

Permalink
fix: fixing nanosockets build error on some platforms
Browse files Browse the repository at this point in the history
Removing support for nanosockets for platforms other than Windows and Linux.
nanosockets is mostly for increasing performance for high CCU servers, which should mostly be Windows and Linux.

Adding optional define to force disable nanosockets EXCLUDE_NANOSOCKETS
Can be used when compiling fails because of nanosockets functions
  • Loading branch information
James-Frowen committed Mar 21, 2023
1 parent c9469a2 commit fbd136c
Show file tree
Hide file tree
Showing 8 changed files with 130 additions and 63 deletions.
42 changes: 42 additions & 0 deletions Assets/Mirage/Runtime/Sockets/Udp/InitUDP.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// windows, linux or standalone c#, unless EXCLUDE_NANOSOCKETS is defined
#if !EXCLUDE_NANOSOCKETS && (UNITY_EDITOR_WIN || UNITY_EDITOR_LINUX || UNITY_STANDALONE_WIN || UNITY_STANDALONE_LINUX || NETCOREAPP || NET_5_0_OR_GREATER)
using NanoSockets;
using UnityEngine;

namespace Mirage.Sockets.Udp
{
public static class InitUDP
{
private static int initCount;

/// <summary>
/// Initializes the NanoSockets native library. If it fails, it resorts to C# Managed Sockets.
/// </summary>
public static void Init()
{
if (initCount == 0)
{
var status = UDP.Initialize();
if (status == Status.Error)
Debug.LogError("Error calling UDP.Initialize");
}

initCount++;
}

public static void Deinit()
{
initCount--;

if (initCount == 0) UDP.Deinitialize();
}

[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
private static void ClearCounter()
{
// todo do we need to call Deinitialize here?
initCount = 0;
}
}
}
#endif
11 changes: 11 additions & 0 deletions Assets/Mirage/Runtime/Sockets/Udp/InitUDP.cs.meta

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions Assets/Mirage/Runtime/Sockets/Udp/NanoEndPoint.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// windows, linux or standalone c#, unless EXCLUDE_NANOSOCKETS is defined
#if !EXCLUDE_NANOSOCKETS && (UNITY_EDITOR_WIN || UNITY_EDITOR_LINUX || UNITY_STANDALONE_WIN || UNITY_STANDALONE_LINUX || NETCOREAPP || NET_5_0_OR_GREATER)
using System;
using Mirage.SocketLayer;
using NanoSockets;
Expand Down Expand Up @@ -50,3 +52,4 @@ public override string ToString()
}
}
}
#endif
12 changes: 9 additions & 3 deletions Assets/Mirage/Runtime/Sockets/Udp/NanoSocket.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
// windows, linux or standalone c#, unless EXCLUDE_NANOSOCKETS is defined
#if !EXCLUDE_NANOSOCKETS && (UNITY_EDITOR_WIN || UNITY_EDITOR_LINUX || UNITY_STANDALONE_WIN || UNITY_STANDALONE_LINUX || NETCOREAPP || NET_5_0_OR_GREATER)
using System;
using Mirage.SocketLayer;
using NanoSockets;

namespace Mirage.Sockets.Udp
{

public sealed class NanoSocket : ISocket, IDisposable
{
public static bool Supported => true;

private Socket socket;
private NanoEndPoint receiveEndPoint;
private readonly int bufferSize;
Expand All @@ -20,7 +25,7 @@ public NanoSocket(UdpSocketFactory factory)
Dispose();
}

private void InitSocket()
private void CreateSocket()
{
socket = UDP.Create(bufferSize, bufferSize);
UDP.SetDontFragment(socket);
Expand All @@ -32,7 +37,7 @@ public void Bind(IEndPoint endPoint)
{
receiveEndPoint = (NanoEndPoint)endPoint;

InitSocket();
CreateSocket();
var result = UDP.Bind(socket, ref receiveEndPoint.address);
if (result != 0)
{
Expand All @@ -56,7 +61,7 @@ public void Connect(IEndPoint endPoint)
{
receiveEndPoint = (NanoEndPoint)endPoint;

InitSocket();
CreateSocket();
var result = UDP.Connect(socket, ref receiveEndPoint.address);
if (result != 0)
{
Expand Down Expand Up @@ -84,3 +89,4 @@ public void Send(IEndPoint endPoint, byte[] packet, int length)
}
}
}
#endif
33 changes: 33 additions & 0 deletions Assets/Mirage/Runtime/Sockets/Udp/NanoSocket_NotSupported.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// windows or linux, unless EXCLUDE_NANOSOCKETS is defined
#if EXCLUDE_NANOSOCKETS || !(UNITY_EDITOR_WIN || UNITY_EDITOR_LINUX || UNITY_STANDALONE_WIN || UNITY_STANDALONE_LINUX || NETCOREAPP || NET_5_0_OR_GREATER)
// these classes are copies of the real classes but throw NotSupported
// this is needed so that NanoSocket scripts can be excluded from builds because this breaks on some targets
using System;
using Mirage.SocketLayer;

namespace Mirage.Sockets.Udp
{
public static class InitUDP
{
public static void Init() => throw new NotSupportedException();
public static void Deinit() => throw new NotSupportedException();
}
public sealed class NanoSocket : ISocket
{
public static bool Supported => false;

public NanoSocket(UdpSocketFactory factory) => throw new NotSupportedException();
public void Bind(IEndPoint endPoint) => throw new NotSupportedException();
public void Connect(IEndPoint endPoint) => throw new NotSupportedException();
public void Close() => throw new NotSupportedException();
public bool Poll() => throw new NotSupportedException();
public int Receive(byte[] buffer, out IEndPoint endPoint) => throw new NotSupportedException();
public void Send(IEndPoint endPoint, byte[] packet, int length) => throw new NotSupportedException();
}
public sealed class NanoEndPoint : IEndPoint
{
public NanoEndPoint(string host, ushort port) => throw new NotSupportedException();
public IEndPoint CreateCopy() => throw new NotSupportedException();
}
}
#endif
11 changes: 11 additions & 0 deletions Assets/Mirage/Runtime/Sockets/Udp/NanoSocket_NotSupported.cs.meta

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// windows, linux or standalone c#, unless EXCLUDE_NANOSOCKETS is defined
#if !EXCLUDE_NANOSOCKETS && (UNITY_EDITOR_WIN || UNITY_EDITOR_LINUX || UNITY_STANDALONE_WIN || UNITY_STANDALONE_LINUX || NETCOREAPP || NET_5_0_OR_GREATER)
/*
* Lightweight UDP sockets abstraction for rapid implementation of message-oriented protocols
* Copyright (c) 2019 Stanislav Denisov
Expand Down Expand Up @@ -246,3 +248,4 @@ public static unsafe class Unsafe {
#endif
}
}
#endif
78 changes: 18 additions & 60 deletions Assets/Mirage/Runtime/Sockets/Udp/UdpSocketFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,11 @@
// #define NANO_SOCKET_ALLOWED
// #endif

using Mirage.SocketLayer;
using System;
using System.Net;
using System.Net.Sockets;
using Mirage.SocketLayer;
using UnityEngine;
using NanoSockets;

namespace Mirage.Sockets.Udp
{
Expand All @@ -27,12 +26,18 @@ public sealed class UdpSocketFactory : SocketFactory, IHasAddress, IHasPort
[Header("NanoSocket-specific Options")]
public int BufferSize = 256 * 1024;


public override int MaxPacketSize => UdpMTU.MaxPacketSize;

// Determines if we can use NanoSockets for socket-level IO. This will be true if either:
// - We *want* to use native library explicitly.
// - We have it set to Automatic selection and NanoSockets is supported.
private bool useNanoSocket => SocketLib == SocketLib.Native || (SocketLib == SocketLib.Automatic && CheckNanosocketsSupport());
private bool useNanoSocket => SocketLib == SocketLib.Native || (SocketLib == SocketLib.Automatic && NanoSocket.Supported);

/// <summary>
/// did this instance call InitUDP.Init? if so then we need to call Deinit too
/// </summary>
[NonSerialized] private bool _udpNeedRelease = false;

string IHasAddress.Address
{
Expand All @@ -46,23 +51,18 @@ int IHasPort.Port
set => Port = checked((ushort)value);
}

private static int initCount;

[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
private static void ClearCounter()
private void Awake()
{
initCount = 0;
if (useNanoSocket)
InitNanosocket();
}

private void Awake()
private void InitNanosocket()
{
// Do not attempt to initialize NanoSockets if we're not using them.
if (!useNanoSocket) return;

if (CheckNanosocketsSupport())
if (NanoSocket.Supported)
{
// Debug.Log("DEBUG: Nanosockets supported on this platform");
InitializeNanoSockets();
InitUDP.Init();
_udpNeedRelease = true;
}
else
{
Expand All @@ -71,31 +71,12 @@ private void Awake()
}
}

/// <summary>
/// Initializes the NanoSockets native library. If it fails, it resorts to C# Managed Sockets.
/// </summary>
private void InitializeNanoSockets()
{
try
{
if (initCount == 0) UDP.Initialize();

initCount++;
}
catch (Exception ex)
{
Debug.LogWarning($"NanoSocket native library not found or failed to load; switching to C# Managed Sockets. Exception returned was:\n{ex}");
SocketLib = SocketLib.Managed;
}
}

private void OnDestroy()
{
if (useNanoSocket)
if (_udpNeedRelease)
{
initCount--;

if (initCount == 0) UDP.Deinitialize();
InitUDP.Deinit();
_udpNeedRelease = false;
}
}

Expand Down Expand Up @@ -189,29 +170,6 @@ private void ThrowIfNotSupported()
/// Is this platform a WebGL-based one?
/// </summary>
private static bool IsWebGL => Application.platform == RuntimePlatform.WebGLPlayer;

/// <summary>
/// Checks to ensure that Nanosockets supports this platform.
/// </summary>
/// <returns>True if supported platform, False if not.</returns>
private static bool CheckNanosocketsSupport()
{
#if UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX
// Short-circut. Mac seemingly has some issues with Nanosockets and
// requires further investigation.
return false;

#elif NETCOREAPP || NET_5_0_OR_GREATER
// Returns true as this would be for Mirage Standalone support.
return true;

#else
// Nanosocket can run inside Windows and Linux. Mac is excluded for now due to above if condition.
return Application.platform == RuntimePlatform.LinuxPlayer
|| Application.platform == RuntimePlatform.WindowsPlayer
|| Application.isEditor;
#endif
}
}

public class EndPointWrapper : IEndPoint
Expand Down

0 comments on commit fbd136c

Please sign in to comment.