1

I am trying to build a secure websocket from unity headless server to WEBGL client. I know its not natively supported. Ive seen nonsecure examples and I have gotten those to work in local builds. WebGL throws out errors due to using https on website and insecure connections on backend. Others have gotten it to work but I cant find an example of "it working" so Im at a loss.

Error

DOMException: Failed to construct 'WebSocket': An insecure WebSocket connection may not be initiated from a page loaded over HTTPS.

Ive tried following Some other guides however as I am learning C# (I come from Python) and don't have a lot of experience in websockets Im not sure on hpw to build out the secure method.

Unity Build : 2019.2

Resources:

using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using WebSocketSharp;

public class WebSocketDemo : MonoBehaviour
{

    // Use this for initialization
    void Start()
    {
        Debug.Log("WebSocket Class");
        // Create WebSocket instance
        using (var ws = new WebSocket("ws://echo.websocket.org"))
        {
            
            Debug.Log(ws.ReadyState);
            
            // Add OnOpen event listener
            ws.OnOpen += (sender, e) => {
  
  
            Debug.Log("WS connected!");
            Debug.Log("WS state: " + ws.ReadyState);

            ws.Send(Encoding.UTF8.GetBytes("Hello from Unity 3D!"));
            };

            // Add OnMessage event listener
            ws.OnMessage += (sender, e) => {

                Debug.Log("WS received message: " + e.Data);// Encoding.UTF8.GetString(e.Data));

                ws.Close();
            };

            // Add OnError event listener
            ws.OnError += (sender, e) => {


            Debug.Log("WS error: " + e.Exception);
            };

            // Add OnClose event listener
         
            // Connect to the server
            ws.Connect();
        }
    }

    // Update is called once per frame
    void Update()
    {

    }
}

In all honesty I need a handout with some code snippets. The above code works for ws but I dont know what else is required for wss on client and server side. As you can tell I'm just reaching out to echo.websocket.org for testing.

Community
  • 1
  • 1
snub-fighter
  • 161
  • 2
  • 14
  • 1
    for Unity WebGL build, I tried this FM WebSocket plugin. ref: https://youtu.be/82_-a7WF3vs –  Nov 25 '19 at 13:11

1 Answers1

1

DOMException: Failed to construct 'WebSocket': An insecure WebSocket connection may not be initiated from a page loaded over HTTPS.

Sounds like you're using an insecure websocket connection. Let's take a look at your URI:

using (var ws = new WebSocket("ws://echo.websocket.org"))

ws means insecure. Let's make it secure instead. Use wss as the protocol. Now this line will look like:

using (var ws = new WebSocket("wss://echo.websocket.org"))

DoctorPangloss
  • 2,994
  • 1
  • 18
  • 22