endel / NativeWebSocket

🔌 WebSocket client for Unity - with no external dependencies (WebGL, Native, Android, iOS, UWP)
Other
1.13k stars 155 forks source link

Quick Fix to make this work with Glitch.com servers #58

Open evnb opened 2 years ago

evnb commented 2 years ago

I was drawn to this repo while trying to communicate between Unity and a Glitch.com server. However, while this works out of the box with a local server it does not automatically work with Glitch and requires slight modifications to both the server and client code:

Client:

"Glitch does require [a User-Agent header] be present in order for your project to accept [web socket] requests," -Glitch Support, QTD by @nicovernio on a Glitch support forum thread.

With this information @nicovernio is able to open the socket using ws.Options.SetRequestHeader( “User-Agent”, “Unity3D”);

However, connection.cs in the example does not interface directly with ws.Options.SetRequestHeader(). Instead this repo abstracts this interaction with the Connect() task of the NativeWebSocket.WebSocket class. To pass a User-Agent header, we pass a String : String dictionary as the optional headers parameter for the NativeWebSocket.WebSocket.WebSocket() constructor.

TLDR: in connection.cs replace

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

with

websocket = new WebSocket("ws://my-glitch-url.glitch.me", new Dictionary<string, string>() { { "User-Agent", "Unity3D" } });

Server:

The server requires a bit more change. For index.js, essentially we can remove all references to express and anything that references those references etc. Then we replace { server } with { port: 3000 } as the parameter to the WebSocket.Server() constructor. Note Glitch only allows ports 3000 or 8080 to be open by default. Next we add a new package.json file in the root directory. It can be similar to the given NodeServer/package.json but with an added element

"engines": {
    "node": "12.x"
  },

Finally open the Glitch project's terminal and run:

npm install

and then

refresh

Then you can close terminal. Glitch will automatically run the server and send its console.log output to the Glitch project's logs.

To see all the changes made, you can check out the diff on the glitch branch of my fork. Thank you @ryqndev for helping to figure this out :)