SFSX WebGL - Websocket connexion blocked on "connecting"

Post here your questions about the Unity / .Net / Mono / Windows 8 / Windows Phone 8 API for SFS2X

Moderators: Lapo, Bax

Ewen
Posts: 2
Joined: 14 Nov 2018, 18:49

SFSX WebGL - Websocket connexion blocked on "connecting"

Postby Ewen » 14 Nov 2018, 19:16

Hi there !

I write to you today because i've been loosing all my hairs for days on one simple little error , i dont find the issue and i dont have anymre hair to take off :) So ... you are my last hope :)

The situation is simple : I try to make functionate a webGL built of my project. When i try to connect to my zone , the smartfox in local stay blocked on trying to "connect" with the server. The log on the server show no activity recorded, i mean no demand of connexion from me. When i debug , the property "is connected" of my smarfox object is false and the property "is connecting" stay on true infinitly (i put a console debug line in the update method) . Well i tryed with the Connector example and with the Tris example , both compiled in webGL build, and it works perfectly... The code i use in my project to connect is exactly the same. When i run my project in the Unity editor in webGL mode, it works perfectly, so i think the configuration of the server is fine with websocket and also my zone... it is just when i compile and use it in the browser that the connexion attempt stay blocked . It seems that the websocket is blocked internally and not sent out to the server ... Do you have an idea ?

Please ... help .. hank you sooo much :)

Here is the code of my login script :

Code: Select all

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using System;
using System.Collections;
using System.Collections.Generic;
using Sfs2X.Core;
using Sfs2X.Util;
using Sfs2X.Entities.Data;
using Sfs2X.Requests;
using System.IO;
using Sfs2X;

public class SFS_Login : MonoBehaviour
{
   
    public bool debug = true;
    public Canvas canvas_UI_Log_Reg;
    public Text title;
    public InputField ipField;
    public InputField portField;
    public Text connectInfoText;
    public GameObject connect_Button;
    public InputField usernameField;
    public InputField passwordField;
    public GameObject login_Button;
    public Text messageText;

    private Sfs2X.SmartFox sfs;



    private bool connectionAttempt = false;
    //private string serverIP = "127.0.0.1";
    //private string serverIP = "192.168.1.5";
    //private string serverIP = "192.168.1.52";
    //private string serverIP = "192.168.1.196";
    //private string serverIP = "192.168.1.208";

    public string zone = "Prepa_Monoscene_II";
    //    private string serverIP = "178.33.71.99";  //--> serveur distant
    public static string serverIP = "37.187.136.36";

    private string serverPort = "9933";
    public static int serverPort_UDP = 9933; // -> port sfs2x udp
    public string serverPort_WebGL = "8080"; // -> port sfs2x webgl

    private string username = "";
    private string password = "";
    private bool isConnected = false;
    private bool isNotFilled = false;
    private string loginErrorMessage = "";
    private string err = "";
    private bool logOK = false;
    private int sfs_Id;
    private string nam = "";
    private string av_Typ = "";
    private string levelCod = "";
    private string[] roomStrings;
    private bool roomListReceived = false;
    private GameObject[] connectElements;
    private GameObject[] loginElements;
    private bool isConnectElements = false;
    private bool isLoginElements = false;
    private SFS_Supervisor scrp_sfsSupervisor;
    private string loggin_register = "false";
    private bool webgl_on = false;

    // Use this for initialization
    void Awake()
    {

        // on etablit la connection au serveur
        if (!SFS2X_Connection.IsInitialized)
        {
            create_sfs2x();
        }
        else
        {
            sfs = SFS2X_Connection.Connection;
        }

        scrp_sfsSupervisor = canvas_UI_Log_Reg.GetComponentInChildren<SFS_Supervisor>();
        isConnectElements = true;
        isLoginElements = true;
        connectElements = GameObject.FindGameObjectsWithTag("Connect");
        loginElements = GameObject.FindGameObjectsWithTag("Login");
        isLoginElements = false;
        isConnected = false;
        isNotFilled = false;
        RegisterSFSSceneCallbacks();
        StaticSwitches.Zone = zone;
    }


    private void create_sfs2x()
    {

        // Initialize SFS2X
#if !UNITY_WEBGL
        sfs = new Sfs2X.SmartFox();
#else
        sfs = new SmartFox(UseWebSocket.WS_BIN);
        webgl_on = true;
#endif

        // Set ThreadSafeMode explicitly, or Windows Store builds will get a wrong default value (false)
        sfs.ThreadSafeMode = true;
    }


    private void RegisterSFSSceneCallbacks()
    {
        sfs.AddEventListener(SFSEvent.CONNECTION, OnConnection);
        sfs.AddEventListener(SFSEvent.CONNECTION_LOST, OnConnectionLost);
        sfs.AddEventListener(SFSEvent.LOGIN, OnLogin);
        sfs.AddEventListener(SFSEvent.LOGIN_ERROR, OnLoginError);
        sfs.AddEventListener(SFSEvent.UDP_INIT, onUdpInit);
    }
    private void UnregisterSFSSceneCallbacks()
    {
        sfs.RemoveEventListener(SFSEvent.CONNECTION, OnConnection);
        sfs.RemoveEventListener(SFSEvent.CONNECTION_LOST, OnConnectionLost);
        sfs.RemoveEventListener(SFSEvent.LOGIN, OnLogin);
        sfs.RemoveEventListener(SFSEvent.LOGIN_ERROR, OnLoginError);
        sfs.RemoveEventListener(SFSEvent.UDP_INIT, onUdpInit);
    }
    public void Start()
    {
        ipField.text = serverIP;
        portField.text = serverPort;

#if !UNITY_WEBGL
            portField.text = serverPort;
#else
        portField.text = serverPort_WebGL;
#endif

    }
    void Update()
    {

        if (sfs != null)
        {
            sfs.ProcessEvents();
//            Debug.Log("sfs connected : " + sfs.IsConnected);
//            Debug.Log("sfs is connecting : " + sfs.IsConnecting);


        if (sfs.IsConnected)
        {
            connectInfoText.text = " Server Connection \nsucceeded !\nLog in Now, or \nCreate a New Player !";
            isConnected = true;
            isConnectElements = false;
            isLoginElements = true;
        }
        else
        {
            //Debug.Log("SmartFox is not Connected");
            isConnected = false;
            isNotFilled = false;
            logOK = false;
            isConnectElements = true;
            isLoginElements = false;
            connectionAttempt = false;
            connectInfoText.text = "Click on \"Connect\"";
        }

        }

        if (!isConnected)
        {
            messageText.text = "Connexion failed !";
        }

        if (isNotFilled)
        {
            messageText.text = "Login Error :\nPlease, fill the \nUsername and \nPassword fields, or \nCreate a New Player !";
        }
        else if (logOK)
        {
            messageText.text = "Your Login is correct ! \nYou are directed to \nthe Base!  \n....... Please wait!";
        }
        else
        {
            messageText.text = err;
        }

        if (isConnectElements)
        {
            title.text = "Connect";
            connect_Button.SetActive(true);
            foreach (GameObject log in loginElements)
            {
                log.SetActive(false);
            }

            foreach (GameObject con in connectElements)
            {
                con.SetActive(true);
            }
        }
        else if (isLoginElements)
        {
            title.text = "Login";
            connect_Button.SetActive(false);
            foreach (GameObject log in loginElements)
            {
                log.SetActive(true);
            }

            foreach (GameObject con in connectElements)
            {
                con.SetActive(false);
            }
        }
        //print("messageText.text = " + messageText.text + "connectInfoText.text = " + connectInfoText.text);
    }


    private void SFS2X_Connect()
    {


        // Set connection parameters
        ConfigData sfs2x_config = new ConfigData();
        sfs2x_config.Host = ipField.text;
        sfs2x_config.Port = Convert.ToInt32(portField.text);
        sfs2x_config.Zone = zone;

        Debug.Log("Host : '" + sfs2x_config.Host+"'");
        Debug.Log("Port : '" + sfs2x_config.Port+"'");
        Debug.Log("Zone : '" + sfs2x_config.Zone+"'");
        Debug.Log("sfssafethreadmode : '" + sfs.ThreadSafeMode + "'");

        // Connect to SFS2X
        sfs.Connect(sfs2x_config);

        sfs.ProcessEvents();

    }

    public void OnConnection(BaseEvent evt)
    {

        if ((bool)evt.Params["success"])
        {

            // Save reference to the SmartFox instance in a static field, to share it among different scenes
            SFS2X_Connection.Connection = sfs;
            isConnectElements = false;
            isLoginElements = true;
        }
        else
        {
            loginErrorMessage = (string)(evt.Params["error"]);
            isConnectElements = true;
            isLoginElements = false;
        }
    }


    public void ConnectMenu()
    {
        Debug.Log("connect button clicked!");
        if (!connectionAttempt)
        {
            connectionAttempt = true;
            SFS2X_Connect();
        }
    }
    public void LoginMenu()
    {
        Debug.Log("Login button clicked!");
        username = usernameField.text;
        password = passwordField.text;
        Debug.Log("username = " + username + ", et password = " + password);
        if (sfs.IsConnected)
        {
            isConnected = true;
            //isNotConnected = false;
            if ((!string.IsNullOrEmpty(username)) || (!string.IsNullOrEmpty(password)))
            {
                isNotFilled = false;
                Debug.Log("je me logue");
                sfs.Send(new Sfs2X.Requests.LoginRequest(username, password));

            }
            else
            {
                isNotFilled = true;
                Debug.Log("les champs sont vides");
            }
        }
        else
        {
            isConnected = false;
            Debug.Log("ne suis plus connecté");
        }
    }
    IEnumerator GiveSomeDelay(float waitTime)
    {
        yield return new WaitForSeconds(waitTime);

    }
    public void CreateInstantMenu()
    {
        Debug.Log("create Instant button clicked!");
        loggin_register = "CreateInstantMenu";
        sfs.Send(new Sfs2X.Requests.LoginRequest(GetRandomString(), "temporary_user"));
    }
    public void CreateAdvancedMenu()
    {
        Debug.Log("create Advanced button clicked!");
        loggin_register = "CreateAdvancedMenu";
        sfs.Send(new Sfs2X.Requests.LoginRequest(GetRandomString(), "temporary_user"));
    }

    public string GetRandomString()
    {
        string path = Path.GetRandomFileName();
        path = path.Replace(".", ""); // Remove period.
        return path;
    }

    public void Back()
    {
        Debug.Log("back Button Clicked!");
        scrp_sfsSupervisor.currentState = SFS_Supervisor.MenuStates.Login;
    }
    public void Exit()
    {
        Debug.Log("Exit Button Clicked!");
        Application.Quit();
    }

    public void OnLogin(BaseEvent evt)
    {

        if (loggin_register.Equals("false")) // si on ne s est pas logge en tant que temporaire pour creer un personnage
        {


            // on recupere les donnes utilisateur
            ISFSObject dataObject = (SFSObject)evt.Params["data"];
            string db_avG = dataObject.GetUtfString("GENDER");
            string av_typ = dataObject.GetUtfString("AV_TYP");
            string levCode = dataObject.GetUtfString("LEVELCODE");
            StaticSwitches.avatarType = av_typ;  // inscrit le type de l'avatar dans une donnée static pour accès multiples
            StaticSwitches.avatarGenre = db_avG;  // inscrit le genre de l'avatar dans une donnée static pour accès multiples
            StaticSwitches.levelCode = levCode;  // inscrit le level code dans une donnée static pour accès multiples

            // si on n ets pas en webgl (c ets a dire pc ou android) on active l udp pour les transformees
            if (!webgl_on)
            {
                sfs.InitUDP(serverIP, serverPort_UDP); // on active le protocole udp pour les transfomees -> sur un port different que le port tcp
                // sfs.InitUDP(); // on active le protocole udp pour les transfomees -> sur le meme port que le port tcp

            }
            else
            {
                logOK = true;

                sfs.Send(new JoinRoomRequest("Cosmic")); // on rejoint la room Cosmic

                // On rejoint la scene de jeu
                SceneManager.LoadScene("LoftAfrica");

                // Remove SFS2X listeners before moving to the main game scene
                UnregisterSFSSceneCallbacks();
            }


        }
        else
        {
            if (loggin_register.Equals("CreateInstantMenu"))
            {
                sfs.Send(new JoinRoomRequest("Earth")); // on rejoint la room Earth
                scrp_sfsSupervisor.currentState = SFS_Supervisor.MenuStates.InstantCreate;

            }
            else if (loggin_register.Equals("CreateAdvancedMenu"))
            {
                sfs.Send(new JoinRoomRequest("Earth")); // on rejoint la room Earth
                scrp_sfsSupervisor.currentState = SFS_Supervisor.MenuStates.AdvancedCreate;

            }
            loggin_register = "false";
        }
    }

    public void OnLoginError(BaseEvent evt)
    {
        // Show error message
        err = "Login failed: " + (string)evt.Params["errorMessage"];
        if (err.Contains("nobody"))
        {
            err = "There is nobody \nwith this username \nand/or password, \nPlease retry or\nCreate a New Player !";
        }

    }

    private void onUdpInit(BaseEvent evt)
    {
        if ((bool)evt.Params["success"])
        {

            logOK = true;

            Debug.Log("UDP operationnel");

            sfs.Send(new JoinRoomRequest("Cosmic")); // on rejoint la room Cosmic

            // On rejoint la scene de jeu
            SceneManager.LoadScene("LoftAfrica");

            // Remove SFS2X listeners before moving to the main game scene
            UnregisterSFSSceneCallbacks();

        }
        else
        {
            Debug.Log("Probleme connection UDP");

            sfs.InitUDP(serverIP, serverPort_UDP); // on active le protocole udp pour les transfomees -> sur un port different que le port tcp
                                                   // sfs.InitUDP(); // on active le protocole udp pour les transfomees -> sur le meme port que le port tcp

        }


    }


    void OnConnectionLost(BaseEvent evt)
    {
        loginErrorMessage = "Connection lost / no connection to server";
    }

    void OnApplicationQuit()
    {
        UnregisterSFSSceneCallbacks();
    }
}

User avatar
Bax
Site Admin
Posts: 4479
Joined: 29 Mar 2005, 09:50
Location: Italy
Contact:

Re: SFSX WebGL - Websocket connexion blocked on "connecting"

Postby Bax » 15 Nov 2018, 10:48

Hello.
We created an empty project in Unity v2018.2.10 with our C# API v1.7.10 to test your exact same code (of course disabling those lines referencing objects we don't have).
Everything works as expected both in the Editor and the browser, both in localhost and using the server installed at 37.187.136.36 as per your code.
Could the browser be the issue? We are testing with Firefox v63.0.1 by double clicking on the html file generated by Unity.
Paolo Bax
The SmartFoxServer Team
Ewen
Posts: 2
Joined: 14 Nov 2018, 18:49

Re: SFSX WebGL - Websocket connexion blocked on "connecting"

Postby Ewen » 16 Nov 2018, 01:07

Thank you sooo much for your time !

The problem finally was coming from the API.
"WebSocket.js" was missing in the project.

Thank you to be there !

Ewen

Return to “SFS2X C# API”

Who is online

Users browsing this forum: No registered users and 2 guests