Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Third Party Mirror WebGL Not working

Discussion in 'Multiplayer' started by natmaxex, Sep 13, 2021.

  1. natmaxex

    natmaxex

    Joined:
    Jul 12, 2012
    Posts:
    68
  2. natmaxex

    natmaxex

    Joined:
    Jul 12, 2012
    Posts:
    68
    Try this
     

    Attached Files:

  3. natmaxex

    natmaxex

    Joined:
    Jul 12, 2012
    Posts:
    68
    here is a free NetworkManagerHUD to crude UI converting.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using Mirror;
    5. using TMPro;
    6.  
    7. public class NetworkManagerUI : MonoBehaviour
    8. {
    9.     NetworkManager manager;
    10.  
    11.     public string addressIp = "192.168.1.204";
    12.  
    13.     public GameObject hostClientButton,
    14.         clientButton,
    15.         serverButton,
    16.         clientReady,
    17.         cancelConnectionAttempt,
    18.         stopHost,
    19.         stopClient,
    20.         stopServer;
    21.     public TMP_Text lable,
    22.         playerName;
    23.     public int buttonId = 0;
    24.  
    25.  
    26.     void Awake()
    27.     {
    28.         manager = GetComponent<NetworkManager>();
    29.     }
    30.  
    31.     // Update is called once per frame
    32.     void Update()
    33.     {
    34.         //server conection statice
    35.         if (!NetworkClient.isConnected && !NetworkServer.active)
    36.         {
    37.             stopHost.SetActive(false);
    38.             stopClient.SetActive(false);
    39.             stopServer.SetActive(false);
    40.             StartButtons();
    41.         }
    42.         else
    43.         {
    44.             serverButton.SetActive(false);
    45.             hostClientButton.SetActive(false);
    46.             clientButton.SetActive(false);
    47.             StatusLabels();
    48.         }
    49.  
    50.         // client ready
    51.         if (NetworkClient.isConnected && !NetworkClient.ready)
    52.         {
    53.             clientReady.SetActive(true);
    54.         }
    55.         else {
    56.             clientReady.SetActive(false);
    57.         }
    58.  
    59.         //Stop Server
    60.         StopButtons();
    61.     }
    62.  
    63.     public void ClientReady(){
    64.         NetworkClient.Ready();
    65.         if (NetworkClient.localPlayer == null)
    66.         {
    67.             NetworkClient.AddPlayer();
    68.         }
    69.     }
    70.  
    71.     void StartButtons()
    72.     {
    73.         if (!NetworkClient.active)
    74.         {
    75.             // Server + Client
    76.             if (Application.platform != RuntimePlatform.WebGLPlayer)
    77.             {
    78.                 hostClientButton.SetActive(true);
    79.  
    80.             }
    81.            
    82.             //Client
    83.             clientButton.SetActive(true);
    84.             manager.networkAddress = addressIp;
    85.  
    86.             // Server Only
    87.             if (Application.platform == RuntimePlatform.WebGLPlayer)
    88.             {
    89.                 lable.text = "(  WebGL cannot be server  )";
    90.                 serverButton.SetActive(false);
    91.             }
    92.             else
    93.             {
    94.                 serverButton.SetActive(true);
    95.             }
    96.             cancelConnectionAttempt.SetActive(false);
    97.         }
    98.         else
    99.         {
    100.             lable.text = "Connecting to " + manager.networkAddress + "..";
    101.             cancelConnectionAttempt.SetActive(true);
    102.         }
    103.     }
    104.  
    105.     public void HostClient() {
    106.         manager.StartHost();
    107.     }
    108.  
    109.     public void Client() {
    110.         manager.StartClient();
    111.     }
    112.  
    113.     public void Server() {
    114.         manager.StartServer();
    115.     }
    116.  
    117.     public void StopTheClient() {
    118.         manager.StopClient();
    119.     }
    120.  
    121.     void StatusLabels()
    122.     {
    123.         // host mode
    124.         // display separately because this always confused people:
    125.         //   Server: ...
    126.         //   Client: ...
    127.         if (NetworkServer.active && NetworkClient.active)
    128.         {
    129.             lable.text = $"<b>Host</b>: running via {Transport.activeTransport}";
    130.         }
    131.         // server only
    132.         else if (NetworkServer.active)
    133.         {
    134.             lable.text = $"<b>Server</b>: running via {Transport.activeTransport}";
    135.         }
    136.         // client only
    137.         else if (NetworkClient.isConnected)
    138.         {
    139.             lable.text = $"<b>Client</b>: connected to {manager.networkAddress} via {Transport.activeTransport}";
    140.         }
    141.     }
    142.  
    143.     void StopButtons()
    144.     {
    145.         // stop host if host mode
    146.         if (NetworkServer.active && NetworkClient.isConnected)
    147.         {
    148.             stopHost.SetActive(true);
    149.         }
    150.  
    151.         // stop client if client-only
    152.         else if (NetworkClient.isConnected)
    153.         {
    154.             stopClient.SetActive(true);
    155.  
    156.         }
    157.         // stop server if server-only
    158.         else if (NetworkServer.active)
    159.         {
    160.             stopServer.SetActive(true);
    161.         }
    162.     }
    163.  
    164.     public void StopHost() {
    165.         // stop host if host mode
    166.         if (NetworkServer.active && NetworkClient.isConnected)
    167.         {
    168.             manager.StopHost();
    169.             //stopHost.SetActive(true);
    170.         }
    171.     }
    172.  
    173.     public void StopMyClient() {
    174.         // stop client if client-only
    175.         if (NetworkServer.active && NetworkClient.isConnected)
    176.         {
    177.             //Nothing
    178.         }
    179.         else if (NetworkClient.isConnected)
    180.         {
    181.             manager.StopClient();
    182.             //stopClient.SetActive(true);
    183.         }
    184.     }
    185.  
    186.     public void StopServer() {
    187.         // stop host if host mode
    188.         if (NetworkServer.active && NetworkClient.isConnected)
    189.         {
    190.             //nothing
    191.         }
    192.  
    193.         // stop client if client-only
    194.         else if (NetworkClient.isConnected)
    195.         {
    196.             //nothing
    197.         }
    198.         // stop server if server-only
    199.         else if (NetworkServer.active)
    200.         {
    201.             manager.StopServer();
    202.             //stopServer.SetActive(true);
    203.         }
    204.     }
    205. }
    206.  
     
  4. kimducbk

    kimducbk

    Joined:
    Jun 9, 2021
    Posts:
    1
    try this
    Code (CSharp):
    1. using System;
    2. using System.Net;
    3. using System.Security.Authentication;
    4. using UnityEngine;
    5. using UnityEngine.Serialization;
    6.  
    7. namespace Mirror.SimpleWeb
    8. {
    9.     public class SimpleWebTransport : Transport
    10.     {
    11.         public const string NormalScheme = "ws";
    12.         public const string SecureScheme = "wss";
    13.  
    14.         [Tooltip("Port to use for server and client")]
    15.         public ushort port = 7778;
    16.  
    17.  
    18.         [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.")]
    19.         public int maxMessageSize = 16 * 1024;
    20.  
    21.         [Tooltip("Max size for http header send as handshake for websockets")]
    22.         public int handshakeMaxSize = 3000;
    23.  
    24.         [Tooltip("disables nagle algorithm. lowers CPU% and latency but increases bandwidth")]
    25.         public bool noDelay = true;
    26.  
    27.         [Tooltip("Send would stall forever if the network is cut off during a send, so we need a timeout (in milliseconds)")]
    28.         public int sendTimeout = 5000;
    29.  
    30.         [Tooltip("How long without a message before disconnecting (in milliseconds)")]
    31.         public int receiveTimeout = 20000;
    32.  
    33.         [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")]
    34.         public int serverMaxMessagesPerTick = 10000;
    35.  
    36.         [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")]
    37.         public int clientMaxMessagesPerTick = 1000;
    38.  
    39.         [Header("Server settings")]
    40.  
    41.         [Tooltip("Groups messages in queue before calling Stream.Send")]
    42.         public bool batchSend = true;
    43.  
    44.         [Tooltip("Waits for 1ms before grouping and sending messages. " +
    45.             "This gives time for mirror to finish adding message to queue so that less groups need to be made. " +
    46.             "If WaitBeforeSend is true then BatchSend Will also be set to true")]
    47.         public bool waitBeforeSend = false;
    48.  
    49.  
    50.         [Header("Ssl Settings")]
    51.         [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")]
    52.         public bool clientUseWss;
    53.  
    54.         public bool sslEnabled;
    55.         [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")]
    56.         public string sslCertJson = "./cert.json";
    57.         public SslProtocols sslProtocols = SslProtocols.Tls12;
    58.  
    59.         [Header("Debug")]
    60.         [Tooltip("Log functions uses ConditionalAttribute which will effect which log methods are allowed. DEBUG allows warn/error, SIMPLEWEB_LOG_ENABLED allows all")]
    61.         [FormerlySerializedAs("logLevels")]
    62.         [SerializeField] Log.Levels _logLevels = Log.Levels.none;
    63.  
    64.         /// <summary>
    65.         /// <para>Gets _logLevels field</para>
    66.         /// <para>Sets _logLevels and Log.level fields</para>
    67.         /// </summary>
    68.         public Log.Levels LogLevels
    69.         {
    70.             get => _logLevels;
    71.             set
    72.             {
    73.                 _logLevels = value;
    74.                 Log.level = _logLevels;
    75.             }
    76.         }
    77.  
    78.         void OnValidate()
    79.         {
    80.             if (maxMessageSize > ushort.MaxValue)
    81.             {
    82.                 Debug.LogWarning($"max supported value for maxMessageSize is {ushort.MaxValue}");
    83.                 maxMessageSize = ushort.MaxValue;
    84.             }
    85.  
    86.             Log.level = _logLevels;
    87.         }
    88.  
    89.         SimpleWebClient client;
    90.         SimpleWebServer server;
    91.  
    92.         TcpConfig TcpConfig => new TcpConfig(noDelay, sendTimeout, receiveTimeout);
    93.  
    94.         public override bool Available()
    95.         {
    96.             return true;
    97.         }
    98.         public override int GetMaxPacketSize(int channelId = 0)
    99.         {
    100.             return maxMessageSize;
    101.         }
    102.  
    103.         void Awake()
    104.         {
    105.             Log.level = _logLevels;
    106.         }
    107.         public override void Shutdown()
    108.         {
    109.             client?.Disconnect();
    110.             client = null;
    111.             server?.Stop();
    112.             server = null;
    113.         }
    114.  
    115.         void LateUpdate()
    116.         {
    117.             ProcessMessages();
    118.         }
    119.  
    120.         /// <summary>
    121.         /// Processes message in server and client queues
    122.         /// <para>Invokes OnData events allowing mirror to handle messages (Cmd/SyncVar/etc)</para>
    123.         /// <para>Called within LateUpdate, Can be called by user to process message before important logic</para>
    124.         /// </summary>
    125.         public void ProcessMessages()
    126.         {
    127.             server?.ProcessMessageQueue(this);
    128.             client?.ProcessMessageQueue(this);
    129.         }
    130.  
    131.         #region Client
    132.         string GetClientScheme() => (sslEnabled || clientUseWss) ? SecureScheme : NormalScheme;
    133.         string GetServerScheme() => sslEnabled ? SecureScheme : NormalScheme;
    134.         public override bool ClientConnected()
    135.         {
    136.             // not null and not NotConnected (we want to return true if connecting or disconnecting)
    137.             return client != null && client.ConnectionState != ClientState.NotConnected;
    138.         }
    139.  
    140.         public override void ClientConnect(string hostname)
    141.         {
    142.             // connecting or connected
    143.             if (ClientConnected())
    144.             {
    145.                 Debug.LogError("Already Connected");
    146.                 return;
    147.             }
    148.  
    149.             UriBuilder builder = new UriBuilder
    150.             {
    151.                 Scheme = GetClientScheme(),
    152.                 Host = hostname,
    153.                 Port = port
    154.             };
    155.  
    156.  
    157.             client = SimpleWebClient.Create(maxMessageSize, clientMaxMessagesPerTick, TcpConfig);
    158.             if (client == null) { return; }
    159.  
    160.             client.onConnect += OnClientConnected.Invoke;
    161.             client.onDisconnect += () =>
    162.             {
    163.                 OnClientDisconnected.Invoke();
    164.                 // clear client here after disconnect event has been sent
    165.                 // there should be no more messages after disconnect
    166.                 client = null;
    167.             };
    168.             client.onData += (ArraySegment<byte> data) => OnClientDataReceived.Invoke(data, Channels.Reliable);
    169.             client.onError += (Exception e) =>
    170.             {
    171.                 OnClientError.Invoke(e);
    172.                 ClientDisconnect();
    173.             };
    174.  
    175.             client.Connect(builder.Uri);
    176.         }
    177.  
    178.         public override void ClientDisconnect()
    179.         {
    180.             // dont set client null here of messages wont be processed
    181.             client?.Disconnect();
    182.         }
    183.  
    184. #if MIRROR_26_0_OR_NEWER
    185.         public override void ClientSend( ArraySegment<byte> segment, int channelId)
    186.         {
    187.             if (!ClientConnected())
    188.             {
    189.                 Debug.LogError("Not Connected");
    190.                 return;
    191.             }
    192.  
    193.             if (segment.Count > maxMessageSize)
    194.             {
    195.                 Log.Error("Message greater than max size");
    196.                 return;
    197.             }
    198.  
    199.             if (segment.Count == 0)
    200.             {
    201.                 Log.Error("Message count was zero");
    202.                 return;
    203.             }
    204.  
    205.             client.Send(segment);
    206.         }
    207. #else
    208.         public override bool ClientSend(int channelId, ArraySegment<byte> segment)
    209.         {
    210.             if (!ClientConnected())
    211.             {
    212.                 Debug.LogError("Not Connected");
    213.                 return false;
    214.             }
    215.  
    216.             if (segment.Count > maxMessageSize)
    217.             {
    218.                 Log.Error("Message greater than max size");
    219.                 return false;
    220.             }
    221.  
    222.             if (segment.Count == 0)
    223.             {
    224.                 Log.Error("Message count was zero");
    225.                 return false;
    226.             }
    227.  
    228.             client.Send(segment);
    229.             return true;
    230.         }
    231. #endif
    232.         #endregion
    233.  
    234.         #region Server
    235.         public override bool ServerActive()
    236.         {
    237.             return server != null && server.Active;
    238.         }
    239.  
    240.         public override void ServerStart()
    241.         {
    242.             if (ServerActive())
    243.             {
    244.                 Debug.LogError("SimpleWebServer Already Started");
    245.             }
    246.  
    247.             SslConfig config = SslConfigLoader.Load(this);
    248.             server = new SimpleWebServer(serverMaxMessagesPerTick, TcpConfig, maxMessageSize, handshakeMaxSize, config);
    249.  
    250.             server.onConnect += OnServerConnected.Invoke;
    251.             server.onDisconnect += OnServerDisconnected.Invoke;
    252.             server.onData += (int connId, ArraySegment<byte> data) => OnServerDataReceived.Invoke(connId, data, Channels.Reliable);
    253.             server.onError += OnServerError.Invoke;
    254.  
    255.             SendLoopConfig.batchSend = batchSend || waitBeforeSend;
    256.             SendLoopConfig.sleepBeforeSend = waitBeforeSend;
    257.  
    258.             server.Start(port);
    259.         }
    260.  
    261.         public override void ServerStop()
    262.         {
    263.             if (!ServerActive())
    264.             {
    265.                 Debug.LogError("SimpleWebServer Not Active");
    266.             }
    267.  
    268.             server.Stop();
    269.             server = null;
    270.         }
    271.  
    272.         public override void ServerDisconnect(int connectionId)
    273.         {
    274.             if (!ServerActive())
    275.             {
    276.                 Debug.LogError("SimpleWebServer Not Active");
    277.                 //return false;
    278.             }
    279.  
    280.             //return server.KickClient(connectionId);
    281.             server.KickClient(connectionId);
    282.         }
    283.  
    284. #if MIRROR_26_0_OR_NEWER
    285.         public override void ServerSend(int connectionId,  ArraySegment<byte> segment, int channelId)
    286.         {
    287.             if (!ServerActive())
    288.             {
    289.                 Debug.LogError("SimpleWebServer Not Active");
    290.                 return;
    291.             }
    292.  
    293.             if (segment.Count > maxMessageSize)
    294.             {
    295.                 Log.Error("Message greater than max size");
    296.                 return;
    297.             }
    298.  
    299.             if (segment.Count == 0)
    300.             {
    301.                 Log.Error("Message count was zero");
    302.                 return;
    303.             }
    304.  
    305.             server.SendOne(connectionId, segment);
    306.             return;
    307.         }
    308. #else
    309.         public override bool ServerSend(System.Collections.Generic.List<int> connectionIds, int channelId, ArraySegment<byte> segment)
    310.         {
    311.             if (!ServerActive())
    312.             {
    313.                 Debug.LogError("SimpleWebServer Not Active");
    314.                 return false;
    315.             }
    316.  
    317.             if (segment.Count > maxMessageSize)
    318.             {
    319.                 Log.Error("Message greater than max size");
    320.                 return false;
    321.             }
    322.  
    323.             if (segment.Count == 0)
    324.             {
    325.                 Log.Error("Message count was zero");
    326.                 return false;
    327.             }
    328.  
    329.             server.SendAll(connectionIds, segment);
    330.             return true;
    331.         }
    332. #endif
    333.  
    334.         public override string ServerGetClientAddress(int connectionId)
    335.         {
    336.             return server.GetClientAddress(connectionId);
    337.         }
    338.  
    339.         public override Uri ServerUri()
    340.         {
    341.             UriBuilder builder = new UriBuilder
    342.             {
    343.                 Scheme = GetServerScheme(),
    344.                 Host = Dns.GetHostName(),
    345.                 Port = port
    346.             };
    347.             return builder.Uri;
    348.         }
    349.         #endregion
    350.     }
    351. }
     
    Caspersure1 likes this.