Mirror WebGL Not working

I made a pc standalone server


that I want to connect from a web client using Mirror.

But it is not connecting!

It works fine with the executable version.

mitch means everything should be working.
port forwarding and IP addresses are all setups correctly.
I tried importing and using SimpleWebTransport but it gave me an error.

This is the code that is giving me an error but it looks fine to me.

Try this

7490693--922139--mirrorSol.PNG

here is a free NetworkManagerHUD to crude UI converting.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Mirror;
using TMPro;

public class NetworkManagerUI : MonoBehaviour
{
    NetworkManager manager;

    public string addressIp = "192.168.1.204";

    public GameObject hostClientButton,
        clientButton,
        serverButton,
        clientReady,
        cancelConnectionAttempt,
        stopHost,
        stopClient,
        stopServer;
    public TMP_Text lable,
        playerName;
    public int buttonId = 0;


    void Awake()
    {
        manager = GetComponent<NetworkManager>();
    }

    // Update is called once per frame
    void Update()
    {
        //server conection statice
        if (!NetworkClient.isConnected && !NetworkServer.active)
        {
            stopHost.SetActive(false);
            stopClient.SetActive(false);
            stopServer.SetActive(false);
            StartButtons();
        }
        else
        {
            serverButton.SetActive(false);
            hostClientButton.SetActive(false);
            clientButton.SetActive(false);
            StatusLabels();
        }

        // client ready
        if (NetworkClient.isConnected && !NetworkClient.ready)
        {
            clientReady.SetActive(true);
        }
        else {
            clientReady.SetActive(false);
        }

        //Stop Server
        StopButtons();
    }

    public void ClientReady(){
        NetworkClient.Ready();
        if (NetworkClient.localPlayer == null)
        {
            NetworkClient.AddPlayer();
        }
    }

    void StartButtons()
    {
        if (!NetworkClient.active)
        {
            // Server + Client
            if (Application.platform != RuntimePlatform.WebGLPlayer)
            {
                hostClientButton.SetActive(true);

            }
           
            //Client
            clientButton.SetActive(true);
            manager.networkAddress = addressIp;

            // Server Only
            if (Application.platform == RuntimePlatform.WebGLPlayer)
            {
                lable.text = "(  WebGL cannot be server  )";
                serverButton.SetActive(false);
            }
            else
            {
                serverButton.SetActive(true);
            }
            cancelConnectionAttempt.SetActive(false);
        }
        else
        {
            lable.text = "Connecting to " + manager.networkAddress + "..";
            cancelConnectionAttempt.SetActive(true);
        }
    }

    public void HostClient() {
        manager.StartHost();
    }

    public void Client() {
        manager.StartClient();
    }

    public void Server() {
        manager.StartServer();
    }

    public void StopTheClient() {
        manager.StopClient();
    }

    void StatusLabels()
    {
        // host mode
        // display separately because this always confused people:
        //   Server: ...
        //   Client: ...
        if (NetworkServer.active && NetworkClient.active)
        {
            lable.text = $"<b>Host</b>: running via {Transport.activeTransport}";
        }
        // server only
        else if (NetworkServer.active)
        {
            lable.text = $"<b>Server</b>: running via {Transport.activeTransport}";
        }
        // client only
        else if (NetworkClient.isConnected)
        {
            lable.text = $"<b>Client</b>: connected to {manager.networkAddress} via {Transport.activeTransport}";
        }
    }

    void StopButtons()
    {
        // stop host if host mode
        if (NetworkServer.active && NetworkClient.isConnected)
        {
            stopHost.SetActive(true);
        }

        // stop client if client-only
        else if (NetworkClient.isConnected)
        {
            stopClient.SetActive(true);

        }
        // stop server if server-only
        else if (NetworkServer.active)
        {
            stopServer.SetActive(true);
        }
    }

    public void StopHost() {
        // stop host if host mode
        if (NetworkServer.active && NetworkClient.isConnected)
        {
            manager.StopHost();
            //stopHost.SetActive(true);
        }
    }

    public void StopMyClient() {
        // stop client if client-only
        if (NetworkServer.active && NetworkClient.isConnected)
        {
            //Nothing
        }
        else if (NetworkClient.isConnected)
        {
            manager.StopClient();
            //stopClient.SetActive(true);
        }
    }

    public void StopServer() {
        // stop host if host mode
        if (NetworkServer.active && NetworkClient.isConnected)
        {
            //nothing
        }

        // stop client if client-only
        else if (NetworkClient.isConnected)
        {
            //nothing
        }
        // stop server if server-only
        else if (NetworkServer.active)
        {
            manager.StopServer();
            //stopServer.SetActive(true);
        }
    }
}

try this

using System;
using System.Net;
using System.Security.Authentication;
using UnityEngine;
using UnityEngine.Serialization;

namespace Mirror.SimpleWeb
{
    public class SimpleWebTransport : Transport
    {
        public const string NormalScheme = "ws";
        public const string SecureScheme = "wss";

        [Tooltip("Port to use for server and client")]
        public ushort port = 7778;


        [Tooltip("Protect against allocation attacks by keeping the max message size small. Otherwise an attacker might send multiple fake packets with 2GB headers, causing the server to run out of memory after allocating multiple large packets.")]
        public int maxMessageSize = 16 * 1024;

        [Tooltip("Max size for http header send as handshake for websockets")]
        public int handshakeMaxSize = 3000;

        [Tooltip("disables nagle algorithm. lowers CPU% and latency but increases bandwidth")]
        public bool noDelay = true;

        [Tooltip("Send would stall forever if the network is cut off during a send, so we need a timeout (in milliseconds)")]
        public int sendTimeout = 5000;

        [Tooltip("How long without a message before disconnecting (in milliseconds)")]
        public int receiveTimeout = 20000;

        [Tooltip("Caps the number of messages the server will process per tick. Allows LateUpdate to finish to let the reset of unity contiue incase more messages arrive before they are processed")]
        public int serverMaxMessagesPerTick = 10000;

        [Tooltip("Caps the number of messages the client will process per tick. Allows LateUpdate to finish to let the reset of unity contiue incase more messages arrive before they are processed")]
        public int clientMaxMessagesPerTick = 1000;

        [Header("Server settings")]

        [Tooltip("Groups messages in queue before calling Stream.Send")]
        public bool batchSend = true;

        [Tooltip("Waits for 1ms before grouping and sending messages. " +
            "This gives time for mirror to finish adding message to queue so that less groups need to be made. " +
            "If WaitBeforeSend is true then BatchSend Will also be set to true")]
        public bool waitBeforeSend = false;


        [Header("Ssl Settings")]
        [Tooltip("Sets connect scheme to wss. Useful when client needs to connect using wss when TLS is outside of transport, NOTE: if sslEnabled is true clientUseWss is also true")]
        public bool clientUseWss;

        public bool sslEnabled;
        [Tooltip("Path to json file that contains path to cert and its password\n\nUse Json file so that cert password is not included in client builds\n\nSee cert.example.Json")]
        public string sslCertJson = "./cert.json";
        public SslProtocols sslProtocols = SslProtocols.Tls12;

        [Header("Debug")]
        [Tooltip("Log functions uses ConditionalAttribute which will effect which log methods are allowed. DEBUG allows warn/error, SIMPLEWEB_LOG_ENABLED allows all")]
        [FormerlySerializedAs("logLevels")]
        [SerializeField] Log.Levels _logLevels = Log.Levels.none;

        /// <summary>
        /// <para>Gets _logLevels field</para>
        /// <para>Sets _logLevels and Log.level fields</para>
        /// </summary>
        public Log.Levels LogLevels
        {
            get => _logLevels;
            set
            {
                _logLevels = value;
                Log.level = _logLevels;
            }
        }

        void OnValidate()
        {
            if (maxMessageSize > ushort.MaxValue)
            {
                Debug.LogWarning($"max supported value for maxMessageSize is {ushort.MaxValue}");
                maxMessageSize = ushort.MaxValue;
            }

            Log.level = _logLevels;
        }

        SimpleWebClient client;
        SimpleWebServer server;

        TcpConfig TcpConfig => new TcpConfig(noDelay, sendTimeout, receiveTimeout);

        public override bool Available()
        {
            return true;
        }
        public override int GetMaxPacketSize(int channelId = 0)
        {
            return maxMessageSize;
        }

        void Awake()
        {
            Log.level = _logLevels;
        }
        public override void Shutdown()
        {
            client?.Disconnect();
            client = null;
            server?.Stop();
            server = null;
        }

        void LateUpdate()
        {
            ProcessMessages();
        }

        /// <summary>
        /// Processes message in server and client queues
        /// <para>Invokes OnData events allowing mirror to handle messages (Cmd/SyncVar/etc)</para>
        /// <para>Called within LateUpdate, Can be called by user to process message before important logic</para>
        /// </summary>
        public void ProcessMessages()
        {
            server?.ProcessMessageQueue(this);
            client?.ProcessMessageQueue(this);
        }

        #region Client
        string GetClientScheme() => (sslEnabled || clientUseWss) ? SecureScheme : NormalScheme;
        string GetServerScheme() => sslEnabled ? SecureScheme : NormalScheme;
        public override bool ClientConnected()
        {
            // not null and not NotConnected (we want to return true if connecting or disconnecting)
            return client != null && client.ConnectionState != ClientState.NotConnected;
        }

        public override void ClientConnect(string hostname)
        {
            // connecting or connected
            if (ClientConnected())
            {
                Debug.LogError("Already Connected");
                return;
            }

            UriBuilder builder = new UriBuilder
            {
                Scheme = GetClientScheme(),
                Host = hostname,
                Port = port
            };


            client = SimpleWebClient.Create(maxMessageSize, clientMaxMessagesPerTick, TcpConfig);
            if (client == null) { return; }

            client.onConnect += OnClientConnected.Invoke;
            client.onDisconnect += () =>
            {
                OnClientDisconnected.Invoke();
                // clear client here after disconnect event has been sent
                // there should be no more messages after disconnect
                client = null;
            };
            client.onData += (ArraySegment<byte> data) => OnClientDataReceived.Invoke(data, Channels.Reliable);
            client.onError += (Exception e) =>
            {
                OnClientError.Invoke(e);
                ClientDisconnect();
            };

            client.Connect(builder.Uri);
        }

        public override void ClientDisconnect()
        {
            // dont set client null here of messages wont be processed
            client?.Disconnect();
        }

#if MIRROR_26_0_OR_NEWER
        public override void ClientSend( ArraySegment<byte> segment, int channelId)
        {
            if (!ClientConnected())
            {
                Debug.LogError("Not Connected");
                return;
            }

            if (segment.Count > maxMessageSize)
            {
                Log.Error("Message greater than max size");
                return;
            }

            if (segment.Count == 0)
            {
                Log.Error("Message count was zero");
                return;
            }

            client.Send(segment);
        }
#else
        public override bool ClientSend(int channelId, ArraySegment<byte> segment)
        {
            if (!ClientConnected())
            {
                Debug.LogError("Not Connected");
                return false;
            }

            if (segment.Count > maxMessageSize)
            {
                Log.Error("Message greater than max size");
                return false;
            }

            if (segment.Count == 0)
            {
                Log.Error("Message count was zero");
                return false;
            }

            client.Send(segment);
            return true;
        }
#endif
        #endregion

        #region Server
        public override bool ServerActive()
        {
            return server != null && server.Active;
        }

        public override void ServerStart()
        {
            if (ServerActive())
            {
                Debug.LogError("SimpleWebServer Already Started");
            }

            SslConfig config = SslConfigLoader.Load(this);
            server = new SimpleWebServer(serverMaxMessagesPerTick, TcpConfig, maxMessageSize, handshakeMaxSize, config);

            server.onConnect += OnServerConnected.Invoke;
            server.onDisconnect += OnServerDisconnected.Invoke;
            server.onData += (int connId, ArraySegment<byte> data) => OnServerDataReceived.Invoke(connId, data, Channels.Reliable);
            server.onError += OnServerError.Invoke;

            SendLoopConfig.batchSend = batchSend || waitBeforeSend;
            SendLoopConfig.sleepBeforeSend = waitBeforeSend;

            server.Start(port);
        }

        public override void ServerStop()
        {
            if (!ServerActive())
            {
                Debug.LogError("SimpleWebServer Not Active");
            }

            server.Stop();
            server = null;
        }

        public override void ServerDisconnect(int connectionId)
        {
            if (!ServerActive())
            {
                Debug.LogError("SimpleWebServer Not Active");
                //return false;
            }

            //return server.KickClient(connectionId);
            server.KickClient(connectionId);
        }

#if MIRROR_26_0_OR_NEWER
        public override void ServerSend(int connectionId,  ArraySegment<byte> segment, int channelId)
        {
            if (!ServerActive())
            {
                Debug.LogError("SimpleWebServer Not Active");
                return;
            }

            if (segment.Count > maxMessageSize)
            {
                Log.Error("Message greater than max size");
                return;
            }

            if (segment.Count == 0)
            {
                Log.Error("Message count was zero");
                return;
            }

            server.SendOne(connectionId, segment);
            return;
        }
#else
        public override bool ServerSend(System.Collections.Generic.List<int> connectionIds, int channelId, ArraySegment<byte> segment)
        {
            if (!ServerActive())
            {
                Debug.LogError("SimpleWebServer Not Active");
                return false;
            }

            if (segment.Count > maxMessageSize)
            {
                Log.Error("Message greater than max size");
                return false;
            }

            if (segment.Count == 0)
            {
                Log.Error("Message count was zero");
                return false;
            }

            server.SendAll(connectionIds, segment);
            return true;
        }
#endif

        public override string ServerGetClientAddress(int connectionId)
        {
            return server.GetClientAddress(connectionId);
        }

        public override Uri ServerUri()
        {
            UriBuilder builder = new UriBuilder
            {
                Scheme = GetServerScheme(),
                Host = Dns.GetHostName(),
                Port = port
            };
            return builder.Uri;
        }
        #endregion
    }
}
1 Like