Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
120 changes: 120 additions & 0 deletions com.unity.multiplayer.mlapi/Prototyping/NetworkingManagerHud.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
using System;
using MLAPI;
using MLAPI.Transports;
using UnityEngine;

namespace MLAPI.Prototyping
{
[RequireComponent(typeof(NetworkingManager))]
[DisallowMultipleComponent]
public class NetworkingManagerHud : MonoBehaviour

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will update names to new standards once they are out 😃

{
NetworkingManager m_NetworkingManager;

Transport m_Transport;

GUIStyle m_LabelTextStyle;

// This is needed to make the port field more convenient. GUILayout.TextField is very limited and we want to be able to clear the field entirely so we can't cache this as ushort.
string m_PortString;

public Vector2 DrawOffset = new Vector2(10, 10);

public Color LabelColor = Color.black;

void Awake()
{
// Only cache networking manager but not transport here because transport could change anytime.
m_NetworkingManager = GetComponent<NetworkingManager>();
m_LabelTextStyle = new GUIStyle(GUIStyle.none);
}

void OnGUI()
{
m_LabelTextStyle.normal.textColor = LabelColor;

m_Transport = m_NetworkingManager.NetworkConfig.NetworkTransport;

if (m_PortString == null)
{
m_PortString = m_Transport.NetworkPort.ToString();
}

GUILayout.BeginArea(new Rect(DrawOffset, new Vector2(200, 200)));

if (m_NetworkingManager.IsRunning)
{
DrawStatusGUI();
}
else
{
DrawConnectGUI();
}

GUILayout.EndArea();
}

void DrawConnectGUI()
{
GUILayout.BeginHorizontal();
GUILayout.Space(10);
GUILayout.Label("Address", m_LabelTextStyle);
GUILayout.Label("Port", m_LabelTextStyle);

GUILayout.EndHorizontal();

GUILayout.BeginHorizontal();

m_Transport.NetworkAddress = GUILayout.TextField(m_Transport.NetworkAddress);
m_PortString = GUILayout.TextField(m_PortString);
if (ushort.TryParse(m_PortString, out ushort port))
{
m_Transport.NetworkPort = port;
}

GUILayout.EndHorizontal();

if (GUILayout.Button("Host (Server + Client)"))
{
m_NetworkingManager.StartHost();
}

GUILayout.BeginHorizontal();

if (GUILayout.Button("Server"))
{
m_NetworkingManager.StartServer();
}

if (GUILayout.Button("Client"))
{
m_NetworkingManager.StartClient();
}

GUILayout.EndHorizontal();
}

void DrawStatusGUI()
{
if (m_NetworkingManager.IsServer)
{
var mode = m_NetworkingManager.IsHost ? "Host" : "Server";
GUILayout.Label($"{mode} active on port: {m_Transport.NetworkPort.ToString()}", m_LabelTextStyle);
}
else
{
if (m_NetworkingManager.IsConnectedClient)
{
GUILayout.Label($"Client connected {m_Transport.NetworkAddress}:{m_Transport.NetworkPort.ToString()}", m_LabelTextStyle);
}
}

GUILayout.Label($"Transport: {m_Transport.GetType().Name}", m_LabelTextStyle);

if (GUILayout.Button("Stop"))
{
m_NetworkingManager.Stop();
}
}
}
}

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

26 changes: 26 additions & 0 deletions com.unity.multiplayer.mlapi/Runtime/Core/NetworkingManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,13 @@ public ulong LocalClientId
/// Gets if we are connected as a client
/// </summary>
public bool IsConnectedClient { get; internal set; }

/// <summary>
/// Gets whether or not a server or client is running.
/// </summary>
public bool IsRunning => IsServer || IsClient;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Adding this for convenience to check whether the networking manager is running as a client, server or host.



/// <summary>
/// The callback to invoke once a client connects. This callback is only ran on the server and on the local client that connects.
/// </summary>
Expand Down Expand Up @@ -606,6 +613,25 @@ public void StopClient()
Shutdown();
}

/// <summary>
/// Stops the running server, client or host.
/// </summary>
public void Stop()

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure whether this is really a nice way to solve this. But I have run into this issue where I just wanted to have MLAPI stop the simulation and I didn't care whether I'm a server, client or host so I added this for convenience.

{
if (IsHost)
{
StopHost();
}
else if(IsServer)
{
StopServer();
}
else if (IsClient)
{
StopClient();
}
}

/// <summary>
/// Starts a Host
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,20 @@ public enum ConnectionIdSpreadMethod
public Transport[] Transports = new Transport[0];
public override ulong ServerClientId => 0;

/// <inheritdoc />
public override string NetworkAddress
{
get => Transports.Any() ? Transports.First().NetworkAddress : default;
set => Array.ForEach(Transports, t => t.NetworkAddress = value);
}

/// <inheritdoc />
public override ushort NetworkPort
{
get => Transports.Any() ? Transports.First().NetworkPort : default;
set => Array.ForEach(Transports, t => t.NetworkPort = value);
}

private byte _lastProcessedTransportIndex;

public override bool IsSupported => true;
Expand Down
13 changes: 13 additions & 0 deletions com.unity.multiplayer.mlapi/Runtime/Transports/Transport.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,19 @@ public abstract class Transport : MonoBehaviour
/// </summary>
public abstract ulong ServerClientId { get; }

/// <summary>
/// Gets or sets the IP address the client uses to connect to the server.
/// For transports which don't use an IP address to connect this property is used to pass a transport specific connection identifier such as a room name.
/// </summary>
public abstract string NetworkAddress { get; set; }

/// <summary>
/// Gets or sets the port this transport should use for networking.
/// In server/host mode this is the port on which the server is exposed.
/// In client mode this is the port
/// </summary>
public abstract ushort NetworkPort { get; set; }

/// <summary>
/// Gets a value indicating whether this <see cref="T:MLAPI.Transports.Transport"/> is supported in the current runtime context.
/// This is used by multiplex adapters.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using MLAPI.Logging;
using MLAPI.Profiling;
using MLAPI.Transports.Tasks;
using UnityEngine;
using UnityEngine.Networking;

namespace MLAPI.Transports.UNET
Expand All @@ -26,8 +27,10 @@ public enum SendMode
public int MaxConnections = 100;
public int MaxSentMessageQueueSize = 128;

public string ConnectAddress = "127.0.0.1";
public int ConnectPort = 7777;
[SerializeField]
string m_ConnectAddress = "127.0.0.1";
[SerializeField]
ushort m_ConnectPort = 7777;
public int ServerListenPort = 7777;
public int ServerWebsocketListenPort = 8887;
public bool SupportWebsocket = false;
Expand Down Expand Up @@ -64,15 +67,25 @@ public enum SendMode
private SocketTask connectTask;
public override ulong ServerClientId => GetMLAPIClientId(0, 0, true);

/// <inheritdoc />
public override string NetworkAddress { get { return m_ConnectAddress; } set { m_ConnectAddress = value; } }

/// <inheritdoc />
public override ushort NetworkPort { get { return m_ConnectPort; } set { m_ConnectPort = value; } }

protected void LateUpdate()
{
if (NetworkTransport.IsStarted && MessageSendMode == SendMode.Queued) {
if (NetworkingManager.Singleton.IsServer) {
for (int i = 0; i < NetworkingManager.Singleton.ConnectedClientsList.Count; i++) {
if (NetworkTransport.IsStarted && MessageSendMode == SendMode.Queued)
{
if (NetworkingManager.Singleton.IsServer)
{
for (int i = 0; i < NetworkingManager.Singleton.ConnectedClientsList.Count; i++)
{
SendQueued(NetworkingManager.Singleton.ConnectedClientsList[i].ClientId);
}
}
else {
else
{
SendQueued(NetworkingManager.Singleton.LocalClientId);
}
}
Expand Down Expand Up @@ -129,15 +142,16 @@ public override void Send(ulong clientId, ArraySegment<byte> data, Channel chann
buffer = data.Array;
}

if (MessageSendMode == SendMode.Queued) {
if (MessageSendMode == SendMode.Queued)
{
RelayTransport.QueueMessageForSending(hostId, connectionId, channelId, buffer, data.Count, out byte error);
}
else {
else
{
RelayTransport.Send(hostId, connectionId, channelId, buffer, data.Count, out byte error);
}
}


public void SendQueued(ulong clientId)
{
if (profilerEnabled)
Expand All @@ -154,17 +168,17 @@ public override NetEventType PollEvent(out ulong clientId, out Channel channel,
{
NetworkEventType eventType = RelayTransport.Receive(out int hostId, out int connectionId, out int channelId, messageBuffer, messageBuffer.Length, out int receivedSize, out byte error);

clientId = GetMLAPIClientId((byte) hostId, (ushort) connectionId, false);
clientId = GetMLAPIClientId((byte)hostId, (ushort)connectionId, false);

receiveTime = UnityEngine.Time.realtimeSinceStartup;

NetworkError networkError = (NetworkError) error;
NetworkError networkError = (NetworkError)error;

if (networkError == NetworkError.MessageToLong)
{
byte[] tempBuffer;

if (temporaryBufferReference != null && temporaryBufferReference.IsAlive && ((byte[]) temporaryBufferReference.Target).Length >= receivedSize)
if (temporaryBufferReference != null && temporaryBufferReference.IsAlive && ((byte[])temporaryBufferReference.Target).Length >= receivedSize)
{
tempBuffer = (byte[])temporaryBufferReference.Target;
}
Expand Down Expand Up @@ -250,7 +264,7 @@ public override SocketTasks StartClient()
SocketTask task = SocketTask.Working;

serverHostId = RelayTransport.AddHost(new HostTopology(GetConfig(), 1), false);
serverConnectionId = RelayTransport.Connect(serverHostId, ConnectAddress, ConnectPort, 0, out byte error);
serverConnectionId = RelayTransport.Connect(serverHostId, m_ConnectAddress, m_ConnectPort, 0, out byte error);

NetworkError connectError = (NetworkError)error;

Expand Down Expand Up @@ -290,7 +304,6 @@ public override SocketTasks StartServer()
{
if (NetworkLog.CurrentLogLevel <= LogLevel.Error) NetworkLog.LogError("Cannot create websocket host when using MLAPI relay");
}

}

int normalHostId = RelayTransport.AddHost(topology, ServerListenPort, true);
Expand All @@ -302,7 +315,7 @@ public override void DisconnectRemoteClient(ulong clientId)
{
GetUnetConnectionDetails(clientId, out byte hostId, out ushort connectionId);

RelayTransport.Disconnect((int) hostId, (int) connectionId, out byte error);
RelayTransport.Disconnect((int)hostId, (int)connectionId, out byte error);
}

public override void DisconnectLocalClient()
Expand All @@ -320,7 +333,7 @@ public override ulong GetCurrentRtt(ulong clientId)
}
else
{
return (ulong)NetworkTransport.GetCurrentRTT((int) hostId, (int) connectionId, out byte error);
return (ulong)NetworkTransport.GetCurrentRTT((int)hostId, (int)connectionId, out byte error);
}
}

Expand Down Expand Up @@ -363,8 +376,8 @@ public void GetUnetConnectionDetails(ulong clientId, out byte hostId, out ushort
}
else
{
hostId = (byte) ((clientId - 1) >> 16);
connectionId = (ushort) ((clientId - 1));
hostId = (byte)((clientId - 1) >> 16);
connectionId = (ushort)((clientId - 1));
}
}

Expand All @@ -390,6 +403,7 @@ public ConnectionConfig GetConfig()
{
throw new InvalidChannelException("Channel " + channelId + " already exists");
}

channelIdToName.Add(channelId, Channels[i].Id);
channelNameToId.Add(Channels[i].Id, channelId);
}
Expand Down
Loading