Git Product home page Git Product logo

nativewebsocket's Introduction

Native WebSocket

This is the simplest and easiest WebSocket library for Unity you can find!

  • No external DLL's required (uses built-in System.Net.WebSockets)
  • WebGL/HTML5 support
  • Supports all major build targets
  • Very simple API
  • (Used in Colyseus Unity SDK)

Consider supporting my work on Patreon | Ko-fi | PayPal

Support me on Patreon

Installation

Requires Unity 2019.1+ with .NET 4.x+ Runtime

Install via UPM (Unity Package Manager)

  1. Open Unity
  2. Open Package Manager Window
  3. Click Add Package From Git URL
  4. Enter URL: https://github.com/endel/NativeWebSocket.git#upm

Install manually

  1. Download this project
  2. Copy the sources from NativeWebSocket/Assets/WebSocket into your Assets directory.

Usage

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

using NativeWebSocket;

public class Connection : MonoBehaviour
{
  WebSocket websocket;

  // Start is called before the first frame update
  async void Start()
  {
    websocket = new WebSocket("ws://localhost:2567");

    websocket.OnOpen += () =>
    {
      Debug.Log("Connection open!");
    };

    websocket.OnError += (e) =>
    {
      Debug.Log("Error! " + e);
    };

    websocket.OnClose += (e) =>
    {
      Debug.Log("Connection closed!");
    };

    websocket.OnMessage += (bytes) =>
    {
      Debug.Log("OnMessage!");
      Debug.Log(bytes);

      // getting the message as a string
      // var message = System.Text.Encoding.UTF8.GetString(bytes);
      // Debug.Log("OnMessage! " + message);
    };

    // Keep sending messages at every 0.3s
    InvokeRepeating("SendWebSocketMessage", 0.0f, 0.3f);

    // waiting for messages
    await websocket.Connect();
  }

  void Update()
  {
    #if !UNITY_WEBGL || UNITY_EDITOR
      websocket.DispatchMessageQueue();
    #endif
  }

  async void SendWebSocketMessage()
  {
    if (websocket.State == WebSocketState.Open)
    {
      // Sending bytes
      await websocket.Send(new byte[] { 10, 20, 30 });

      // Sending plain text
      await websocket.SendText("plain text message");
    }
  }

  private async void OnApplicationQuit()
  {
    await websocket.Close();
  }

}

Demonstration

1. Start the local WebSocket server:

cd Server
npm install
npm start

2. Open the NativeWebSocket/Assets/WebSocketExample/WebSocketExampleScene.unity on Unity and Run.

Acknowledgements

Big thanks to Jiri Hybek. This implementation is based on his work.

License

Apache 2.0

nativewebsocket's People

Contributors

codingben avatar endel avatar insthync avatar kentakang avatar mentaman avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

nativewebsocket's Issues

Unity app Crashing when reopening from Background after idling for ~10+ minutes

This crash seems like it only occurs in iOS 13+ and is intermittent. I get it occur about 20% of the time. The error in xCode reads something like IL2CPP Threadpool worker (44): EXC_BAD_ACCESS (code=1, address=0x18). The address part slightly changes sometimes, but the rest is the same.

I created an empty project where I just connect to our server and then minimize the app by tapping the power button on the iPad. After waiting ~10 minutes or so reopen the app. About 20% of the time, the app will crash. Xcode doesn't seem to be logging anything from Unity. I just get the error After applicationwillenterforeground and before applicationdidbecomeactive. I've tried debugging this for a while now, with little luck because of the lack of logging. I did notice during debugging when I commented out the await Receive() call in Websocket.cs Connect() it stopped crashing, but of course I can't receive messages at that point.

Has anyone else had a similar issue? Anyone have any ideas?

Why is Connect method blocking

Hey @endel, I just noticed that the Connect method is blocking because execution doesnt continue after calling method from another script, is this intentional? Also, can this be created outside a MonoBehaviour class? I say it because of the code inside the Update method for editor and webgl.

Thanks anyway for such a simple and amazing package!

The remote party closed the WebSocket connection without completing the close handshake.

Using Reserve seat API to join in a room, and when there is a WebSocket connection drops unexpectedly, its not reconnecting and getting an error " The remote party closed the WebSocket connection without completing the close handshake." with error code : 1006.

Step to reproduce:

  1. Join room by Seat reserve call - (Independent of matchmaking of Colyseus)
  2. After successful seat reserve call
  3. Ping pong should be started
  4. Once get connected try to close the internet for a few seconds or if your internet gets disconnected for some reason.
    you will get the issue right there

Trying to build for WebGL fails

I added these scripts to my Unity project, and changed the name of the WebSocket class to something else to avoid the same name as some other script I currently have.

Building for WebGL fails with the following message (see below)
Could you maybe shed some light on what is missing or going wrong?

Failed running "C:/Program Files/Unity/Hub/Editor/2019.3.1f1/Editor/Data/PlaybackEngines/WebGLSupport\BuildTools\Emscripten_Win\python\2.7.5.3_64bit\python.exe" -E "C:/Program Files/Unity/Hub/Editor/2019.3.1f1/Editor/Data/PlaybackEngines/WebGLSupport\BuildTools\Emscripten\emcc" @"C:\Users\heerpbuld\Documents\Code\Productive\unity\Unity4MCTS\Assets..\Temp\emcc_arguments.resp"

stdout:
stderr:warning: unexpected number of arguments 1 in call to '__cxa_pure_virtual', should be 0warning: unexpected number of arguments 2 in call to '_ZN6il2cpp6icalls8mscorlib6System6String22RedirectToCreateStringEv', should be 0warning: unexpected number of arguments 4 in call to '_ZN6il2cpp6icalls8mscorlib6System6String22RedirectToCreateStringEv', should be 0warning: unexpected number of arguments 2 in call to '_ZN6il2cpp6icalls8mscorlib6System6String22RedirectToCreateStringEv', should be 0warning: unexpected number of arguments 4 in call to '_ZN6il2cpp6icalls8mscorlib6System6String22RedirectToCreateStringEv', should be 0warning: unexpected number of arguments 5 in call to '_ZN6il2cpp6icalls8mscorlib6System6String22RedirectToCreateStringEv', should be 0warning: unexpected number of arguments 4 in call to '_ZN6il2cpp6icalls8mscorlib6System6String22RedirectToCreateStringEv', should be 0warning: unexpected number of arguments 2 in call to '_ZN6il2cpp6icalls8mscorlib6System6String22RedirectToCreateStringEv', should be 0warning: unexpected number of arguments 3 in call to '_ZN6il2cpp6icalls8mscorlib6System6String22RedirectToCreateStringEv', should be 0error: unresolved symbol: Closeerror: unresolved symbol: Helloerror: unresolved symbol: InitWebSocketerror: unresolved symbol: Senderror: unresolved symbol: StateAborting compilation due to previous errors | undefinedTraceback (most recent call last): File "C:\Program Files\Unity\Hub\Editor\2019.3.1f1\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\emcc.py", line 3063, in sys.exit(run()) File "C:\Program Files\Unity\Hub\Editor\2019.3.1f1\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\emcc.py", line 1780, in run final = shared.Building.emscripten(final, append_ext=False, extra_args=extra_args) File "C:\Program Files\Unity\Hub\Editor\2019.3.1f1\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\tools\shared.py", line 2274, in emscripten emscripten._main(cmdline) File "C:\Program Files\Unity\Hub\Editor\2019.3.1f1\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\emscripten.py", line 2233, in _main return temp_files.run_and_clean(lambda: main( File "C:\Program Files\Unity\Hub\Editor\2019.3.1f1\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\tools\tempfiles.py", line 93, in run_and_clean return func() File "C:\Program Files\Unity\Hub\Editor\2019.3.1f1\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\emscripten.py", line 2238, in DEBUG=DEBUG, File "C:\Program Files\Unity\Hub\Editor\2019.3.1f1\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\emscripten.py", line 2164, in main temp_files=temp_files, DEBUG=DEBUG) File "C:\Program Files\Unity\Hub\Editor\2019.3.1f1\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\emscripten.py", line 86, in emscript glue, forwarded_data = compiler_glue(metadata, libraries, compiler_engine, temp_files, DEBUG) File "C:\Program Files\Unity\Hub\Editor\2019.3.1f1\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\emscripten.py", line 218, in compiler_glue glue, forwarded_data = compile_settings(compiler_engine, libraries, temp_files) File "C:\Program Files\Unity\Hub\Editor\2019.3.1f1\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\emscripten.py", line 541, in compile_settings cwd=path_from_root('src'), error_limit=300) File "C:\Program Files\Unity\Hub\Editor\2019.3.1f1\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\tools\jsrun.py", line 132, in run_js raise Exception('Expected the command ' + str(command) + ' to finish with return code ' + str(assert_returncode) + ', but it returned with code ' + str(proc.returncode) + ' instead! Output: ' + str(ret)[:error_limit])Exception: Expected the command ['C:/Program Files/Unity/Hub/Editor/2019.3.1f1/Editor/Data\Tools\nodejs\node.exe', '--stack_size=8192', '--max-old-space-size=4096', 'C:\Program Files\Unity\Hub\Editor\2019.3.1f1\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\src\compiler.js', 'C:\Users\HEERPB~1\AppData\Local\Temp\tmpf_dgp6.txt', 'C:\Program Files\Unity\Hub\Editor\2019.3.1f1\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\lib\Audio.js', 'C:\Program Files\Unity\Hub\Editor\2019.3.1f1\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\lib\Cursor.js', 'C:\Program Files\Unity\Hub\Editor\2019.3.1f1\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\lib\Eval.js', 'C:\Program Files\Unity\Hub\Editor\2019.3.1f1\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\lib\FileSystem.js', 'C:\Program Files\Unity\Hub\Editor\2019.3.1f1\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\lib\Logging.js', 'C:\Program Files\Unity\Hub\Editor\2019.3.1f1\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\lib\Profiler.js', 'C:\Program Files\Unity\Hub\Editor\2019.3.1f1\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\lib\SystemInfo.js', 'C:\Program Files\Unity\Hub\Editor\2019.3.1f1\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\lib\UnetWebSocket.js', 'C:\Program Files\Unity\Hub\Editor\2019.3.1f1\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\lib\Video.js', 'C:\Program Files\Unity\Hub\Editor\2019.3.1f1\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\lib\WebCam.js', 'C:\Program Files\Unity\Hub\Editor\2019.3.1f1\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\lib\WebRequest.js', 'C:\Users\heerpbuld\Documents\Code\Productive\unity\Unity4MCTS\Assets\Imported Assets\WebSocket\WebSocket.jslib', 'C:\Program Files\Unity\Hub\Editor\2019.3.1f1\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\Emscripten\src\library_pthread_stub.js'] to finish with return code 0, but it returned with code 1 instead! Output: // The Module object: Our interface to the outside world. We import// and export values on it. There are various ways Module can be used:// 1. Not defined. We create it here// 2. A function parameter, function(Module) { ..generated code.. }// 3. pre-run appended it, var Module = {}; ..generated
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)

Cant Recieve JSON

hi, im trying to send Json object from server to client ,


var sendingInfo = { timer: null, otherPlayersNameAndNumber: [] }

im getting [object object] as a debug.log on unity on websocket.OnMessage, and when i try to deserialize from JSON in OnMessage , i get error from websocket.OnError even though Json match with my class in unity.
I also tried to create an object with JSON.stringify(sendingInfo) on server side and send, however this time i wont get any debug.log from OnMessage.

Edit: Opps ,sorry. by using JSON.stringify(sendingInfo) on server, looks like i was getting debug.log , just logs were messed that is why i couldnt see.

Can i send string and bytearray together?

The API I'm trying to use, wants me to send data in the following manor:

websocket.emit("binaryData", data);

Does NativeWebSockets support this? or can i only sent plain text OR byteArray separately?

Thanks

Quick Fix to make this work with Glitch.com servers

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 :)

I Have basic Project Android connection Error! Please Help me

Please Help me .

I get Android this error .

Unable to connect to the remote server
System.Action`1:Invoke(T)
NativeWebSocket.WebSocketErrorEventHandler:Invoke(String)
NativeWebSocket.d__26:MoveNext()
UnityEngine.UnitySynchronizationContext:Exec()

Unity Application freezing when network connection is lost. Is there any timeout parameter that can be configured ?

Hi @endel, when I was testing, I came across this issue.

Context: Messages would be published from my application continuously with a frequency of 20 messages per second. When the application is running and the network connection is stable, and all the messages sent through this function - SendText are being successfully delivered.

Issue: With the above-mentioned context, in such a case when the internet gets disconnected, the Unity Application is getting frozen. When checked with the profiler, below is the information gathered.
WebSocketSendMessageFunctionProfiler

The application is coming back to a normal state after ~16 seconds. And when the application comes back to a normal state, the below error is being logged in the console. And only then OnClose callback of WebSocket is getting invoked.
WebSocketExceptionInfo.txt

I assume this might happen due to the setting "-1" as a timeout parameter for a task.
If that is the case, can you please let me know on how to configure the timeout parameter?

Please make Unity Package

Hey!

Thanks a lot for the native web socket. I'd ask you to create a "package.json" file so that we can add this package via git url to our Unity package manager.

See example with in my repository ui-manager. I also have a CI (GitHub Actions) that adds the latest commits to the upm branch.

If you want, I can contribute and make this repository the same as ui-manager so that we can use NativeWebSocket as a package instead of adding it to the Assets folder.

Alternative using UniTask

Hi there! I used the code from @endel and @jirihybek (thanks a lot for the good work!) and changed it up a bit to make it work with UniTask and therefore providing a more similar interface to System.Net.WebSockets. You can find it here: https://github.com/Iblis/UniTaskWebSocket

The changes are breaking the established interface of NativeWebSocket, therefore I thought it makes more sense to create a new repo for it.

Network Disconnects - Abort or Close

I came across few issues with disconnect and reconnect scenarios. I am using C# version of Websocket:

  • calling websocket.Close() hangs the client when we lose internet connection or when 100% packets drop due to poor connection (this scenario, client is connected to network, there is severe packet loss)
  • websocket.Close() completes once network connectivity happens. But at that point, there is no reason to disconnect.
  • I did not check as to when timeout happens after websocket.close() is called and network connectivity never happens. Client hangs for quite a long time on mac.

Note: I have used Network Link Conditioner on Mac to simulate network conditions apart from testing on Windows and Android. Each one of them behaves little differently. This is because OS level network settings.

ClientWebSocket has three methods CloseAsync, CloseOutputAsyncand Abort.

  • CloseAsync and CloseOutputAsync are for exchanging close frames between Server and Client. This for a more orderly shutdown when client wants to disconnect or server wants to terminate connection.
  • Abort aborts connection and any pending I/O operations. This is a sync call and returns immediately.

Now coming back to NativeWebSocket, exposes websocket.Close() which calls CloseAsync() on ClientWebSocket. If network is disconnected, there is no point in calling CloseAsync or CloseOutputAsync as they are for terminating connections with acknowledgements. And there is no Abort method exists or a way to access ClientWebSocket as it is private.

For anyone who is curious as to how we detect network disconnects in our client - we use PingPong to send and receive msgs every n seconds/milliseconds. After sending a Ping, we don't receive a Pong within next n milliseconds - it is a disconnect.

I researched more about CloseAsync vs CloseOutputAsync and came across this article - https://mcguirev10.com/2019/08/17/how-to-close-websocket-correctly.html

Discussion points:

  • Should there be a Abort method on WebSocket in this library ?
  • Should CloseOutputAsync be called instead of CloseAsync as client is initiating termination of websockets as per this article ?

Can't receive binary data (Unity 2020.1.4f1) in WebGL builds (works in other builds)

Dear @endel ,

Thank you a lot for the great library. I can't make it work for WebGL builds though (at least in Unity 2020.1.4f1, I haven't tried other versions yet). The same code works just fine in non-WebGL builds.
When I enable debug in the jslib, I get in the console (Google Chrome, Windows 10):

webgl.framework.js:3635 [JSLIB WebSocket] Connected.
webgl.framework.js:3293 Connection established 
(Filename: ./Runtime/Export/Debug/Debug.bindings.h Line: 35)


webgl.framework.js:3639 [JSLIB WebSocket] Received message: ArrayBuffer(11548) {}[[Int8Array]]: Int8Array(11548) [12, 0, 0, 0, 8, 0, 14, 0, 7, 0, 8, 0, 8, 0, 0, 0, 0, 0, 0, 2, 12, 0, 0, 0, 0, 0, 6, 0, 8, 0, 4, 0, 6, 0, 0, 0, 4, 0, 0, 0, -49, 2, 0, 0, 78, -47, -41, -64, 83, 116, -36, 64, -49, 68, -72, -65, 96, -61, -77, 63, -40, -93, -70, -64, -14, -46, -7, 64, 85, -63, 104, -66, 96, -61, -77, 63, 53, 17, -36, -64, -72, 30, -41, 64, 43, -87, -53, -65, 58, 35, -62, 63, 9, -118, -65, -64, -8, 49, -10, 64, …][[Int16Array]]: Int16Array(5774) [12, 0, 8, 14, 7, 8, 8, 0, 0, 512, 12, 0, 0, 6, 8, 4, 6, 0, 4, 0, 719, 0, -11954, -16169, 29779, 16604, 17615, -16456, -15520, 16307, -23592, -16198, -11534, 16633, -16043, -16792, -15520, 16307, 4405, -16164, 7864, 16599, -22229, -16437, 9018, 16322, -30199, -16193, 12792, 16630, 0, 0, 9018, 16322, 10486, -16092, 14995, 16493, 15834, -16679, -6606, 16478, 3251, -16103, -25690, 16550, -31793, 16195, 21538, 16073, 10800, -16105, -7235, 16554, 4195, 16280, 14575, 16515, 13946, -16205, -5453, 16655, 23488, -16344, -30828, -16185, 16043, -16201, 29571, 16650, 15833, 16473, 24641, -16347, 2098, -16110, -20447, 16596, 32694, 16157, …][[Int32Array]]: Int32Array(2887) [12, 917512, 524295, 8, 33554432, 12, 393216, 262152, 6, 4, 719, -1059598002, 1088189523, -1078442801, 1068745568, -1061510184, 1090114290, -1100431019, 1068745568, -1059319499, 1087839928, -1077171925, 1069687610, -1061189111, 1089876472, 0, 1069687610, -1054594826, 1080900243, -1093059110, 1079961138, -1055322957, 1084660646, 1061389263, 1053381666, -1055446480, 1084941245, 1066930275, 1082341615, -1061996934, 1091562163, -1071096896, -1060665452, -1061732693, 1091203971, 1079590361, -1071292351, -1055782862, 1087680545, 1058897846, -1088540671, -1054204756, 1081463118, -1098448959, 1079961138, -1054854873, 1084724609, -1092550760, 1079961138, -1055589190, 1086778979, 1070235386, 1079961138, -1054676615, 1085811563, 1044001860, 1076427017, -1055058086, 1087070904, -1103481788, 1076427017, -1056123754, 1089441943, 1072218452, 1076427017, -1054485774, 1085110485, 1044001860, 1076898038, -1055913306, 1089023770, 1070693404, 1076898038, -1055462419, 1088147161, 1062304628, -1088540671, -1055284474, 1087592884, 1065354055, -1095986734, -1054042227, 1083036821, -1083653635, 1079254397, -1054226775, 1085854345, 1052797484, 1076427017, -1055868217, …][[Uint8Array]]: Uint8Array(11548) [12, 0, 0, 0, 8, 0, 14, 0, 7, 0, 8, 0, 8, 0, 0, 0, 0, 0, 0, 2, 12, 0, 0, 0, 0, 0, 6, 0, 8, 0, 4, 0, 6, 0, 0, 0, 4, 0, 0, 0, 207, 2, 0, 0, 78, 209, 215, 192, 83, 116, 220, 64, 207, 68, 184, 191, 96, 195, 179, 63, 216, 163, 186, 192, 242, 210, 249, 64, 85, 193, 104, 190, 96, 195, 179, 63, 53, 17, 220, 192, 184, 30, 215, 64, 43, 169, 203, 191, 58, 35, 194, 63, 9, 138, 191, 192, 248, 49, 246, 64, …][0 … 9999][0 … 99][100 … 199][200 … 299][300 … 399][400 … 499][500 … 599][600 … 699][700 … 799][800 … 899][900 … 999][1000 … 1099][1100 … 1199][1200 … 1299][1300 … 1399][1400 … 1499][1500 … 1599][1600 … 1699][1700 … 1799][1800 … 1899][1900 … 1999][2000 … 2099][2100 … 2199][2200 … 2299][2300 … 2399][2400 … 2499][2500 … 2599][2600 … 2699][2700 … 2799][2800 … 2899][2900 … 2999][3000 … 3099][3100 … 3199][3200 … 3299][3300 … 3399][3400 … 3499][3500 … 3599][3600 … 3699][3700 … 3799][3800 … 3899][3900 … 3999][4000 … 4099][4100 … 4199][4200 … 4299][4300 … 4399][4400 … 4499][4500 … 4599][4600 … 4699][4700 … 4799][4800 … 4899][4900 … 4999][5000 … 5099][5100 … 5199][5200 … 5299][5300 … 5399][5400 … 5499][5500 … 5599][5600 … 5699][5700 … 5799][5800 … 5899][5900 … 5999][6000 … 6099][6100 … 6199][6200 … 6299][6300 … 6399][6400 … 6499][6500 … 6599][6600 … 6699][6700 … 6799][6800 … 6899][6900 … 6999][7000 … 7099][7100 … 7199][7200 … 7299][7300 … 7399][7400 … 7499][7500 … 7599][7600 … 7699][7700 … 7799][7800 … 7899][7900 … 7999][8000 … 8099][8100 … 8199][8200 … 8299][8300 … 8399][8400 … 8499][8500 … 8599][8600 … 8699][8700 … 8799][8800 … 8899][8900 … 8999][9000 … 9099][9100 … 9199][9200 … 9299][9300 … 9399][9400 … 9499][9500 … 9599][9600 … 9699][9700 … 9799][9800 … 9899][9900 … 9999][10000 … 11547]__proto__: TypedArraybyteLength: (...)__proto__: ArrayBufferbyteLength: (...)constructor: ƒ ArrayBuffer()slice: ƒ slice()Symbol(Symbol.toStringTag): "ArrayBuffer"get byteLength: ƒ byteLength()__proto__: Object

webgl.framework.js:3885 Uncaught 25674192
___resumeException @ webgl.framework.js:3885
_ReversePInvokeWrapper_WebSocketFactory_DelegateOnMessageEvent_mE581241D6F0AD9A885B109DF8F0A99B98D04CAF1 @ webgl.wasm:0xb29f06
dynCall_viii @ webgl.wasm:0xbcc891
(anonymous) @ webgl.framework.js:24620
(anonymous) @ webgl.framework.js:3646

Is there anything I could check to see why I get this ___resumeException?

Btw, as suggested in Unity forums, I tried replacing Runtime.dynCall stuff with dynCall_viii(...) like calls. Though works the same as the Runtime version (f.e. successfully handles openning the connection) it still fails (the same way) to deliver the binary message with that ___resumeException.

Thank you a lot!

Wss Connection and authentication

Hi everyone, I am totally new to this and can't find a clear explanation of how to make this webSocket work.

I need to be able to connect to a WSS and put my login and password.

So if I have a url = wss://example.com
a login = "pedro
password = "issou

what should I do ? I saw that you can put headers but I don't know how it works, and when I test things I get errors :/

wss protocol does not work when build on UWP

I'm using your great library for implement websockets on Hololens.
If I use a ws protocol, it works on Unity Editor and Hololens.
If I use wss, it works on Unity Editor but does not work on Hololens.

Seems a certificate error, because I get this error on the Hololens log:
Curl error 51: Cert verify failed: UNITYTLS_X509VERIFY_FLAG_NOT_TRUSTED

Here the errors I got:

A call to SSPI failed, see inner exception.

Mono.Security.Interface.TlsException: Handshake failed - error code: UNITYTLS_INTERNAL_ERROR, verify result: UNITYTLS_X509VERIFY_FLAG_NOT_TRUSTED
at Mono.Unity.Debug.CheckAndThrow (Mono.Unity.UnityTls+unitytls_errorstate errorState, Mono.Unity.UnityTls+unitytls_x509verify_result verifyResult, System.String context, Mono.Security.Interface.AlertDescription defaultAlert) [0x00036] in <0d3e94ab2a1c4d2a8582ccee7031f5c6>:0
at Mono.Unity.UnityTlsContext.ProcessHandshake () [0x00082] in <0d3e94ab2a1c4d2a8582ccee7031f5c6>:0
at Mono.Net.Security.MobileAuthenticatedStream.ProcessHandshake (Mono.Net.Security.AsyncOperationStatus status) [0x0003e] in <0d3e94ab2a1c4d2a8582ccee7031f5c6>:0
at (wrapper remoting-invoke-with-check) Mono.Net.Security.MobileAuthenticatedStream.ProcessHandshake(Mono.Net.Security.AsyncOperationStatus)
at Mono.Net.Security.AsyncHandshakeRequest.Run (Mono.Net.Security.AsyncOperationStatus status) [0x00006] in <0d3e94ab2a1c4d2a8582ccee7031f5c6>:0
at Mono.Net.Security.AsyncProtocolRequest+d__24.MoveNext () [0x000ff] in <0d3e94ab2a1c4d2a8582ccee7031f5c6>:0
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in :0
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in :0
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in :0
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in :0
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable+ConfiguredTaskAwaiter.GetResult () [0x00000] in :0
at Mono.Net.Security.AsyncProtocolRequest+d__23.MoveNext () [0x0008b] in <0d3e94ab2a1c4d2a8582ccee7031f5c6>:0

at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in :0
at Mono.Net.Security.MobileAuthenticatedStream+d__47.MoveNext () [0x00254] in <0d3e94ab2a1c4d2a8582ccee7031f5c6>:0
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in :0
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in :0
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in :0
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in :0
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable+ConfiguredTaskAwaiter.GetResult () [0x00000] in :0
at System.Net.WebSockets.WebSocketHandle+d__24.MoveNext () [0x00199] in <0d3e94ab2a1c4d2a8582ccee7031f5c6>:0

System.Security.Authentication.AuthenticationException

at System.Net.WebSockets.WebSocketHandle+d__24.MoveNext () [0x00391] in <0d3e94ab2a1c4d2a8582ccee7031f5c6>:0
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in :0
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in :0
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in :0
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in :0
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable+ConfiguredTaskAwaiter.GetResult () [0x00000] in :0
at System.Net.WebSockets.ClientWebSocket+d__16.MoveNext () [0x000d1] in <0d3e94ab2a1c4d2a8582ccee7031f5c6>:0
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in :0
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in :0
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in :0
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in :0
at System.Runtime.CompilerServices.TaskAwaiter.GetResult () [0x00000] in :0
at NativeWebSocket.WebSocket+d__19.MoveNext () [0x0005a] in C:\Users\manuel\development\unityProjects\NativeWebsocket\Assets\Scripts\WebSocket.cs:306

[Idea] Move Receive() to it's own Listen() method

Current Receive() is called at the end of Connect(). This means that if you ever want to await the Connect() call (so that you move on when it's connected), it won't actually return until the socket is disconnected. Moving it to it's own Listen() method would allow for that.

Something like:

// Websocket.cs
// 1) Remove the "await Receive()" call from the end of Connect()
// 2) Add an empty Listen() method in the WebGL implementation for compatibility
// 3) Add the following method:
public async void Listen()
{
	try
	{
		await Receive();
	}
	catch (Exception ex)
	{
		OnError?.Invoke(ex.Message);
		OnClose?.Invoke(WebSocketCloseCode.Abnormal);
	}
	finally
	{
		if (m_Socket != null)
		{
			m_TokenSource.Cancel();
			m_Socket.Dispose();
		}
	}
}

This lets you handle the websocket connection like so:

// WebsocketConnection.cs
public async Task ConnectAsync( string uri )
{
	if( this.isOpen )
	{
		Debug.LogWarning( "[WebSocketConnection] Trying to connect a websocket, but we're already open" );
		return; // we're already connected
	}

	// start our connection
	this.m_uri = uri;
	this.m_socket = new WebSocket( this.m_uri );
	
	// add our events
	this.m_socket.OnOpen += this._onWebSocketOpen;
	this.m_socket.OnClose += this._onWebSocketClose;
	this.m_socket.OnError += this._onWebSocketError;
	this.m_socket.OnMessage += this._onWebSocketMessage;

	Trace.Log( $"[WebSocketConnection] Opening a new connection to {this.m_uri}" );
	await this.m_socket.Connect();

	// wait until the socket is actually open
	await new WaitUntil( () => this.isOpen );
}

public void Update()
{
#if !UNITY_WEBGL || UNITY_EDITOR
	if( this.isOpen )
		this.m_socket.DispatchMessageQueue();
#endif
}

// called when our socket is open and ready for business
private void _onWebSocketOpen()
{
	Debug.Log( $"[WebSocketConnection] Connection to {this.m_uri} open!" );

	// start listening on the socket (NOTE: we're not awaiting here)
	this.m_socket.Listen();
}

Then actually using it in a method becomes much simpler. You can connect with something like:

public async void JoinGame()
{
	// check if we need to connect
	if( !this.m_websocketConnection.isConnected )
		await this.m_websocketConnection.ConnectAsync( this.m_websocketServerURI );

	this.m_websocketConnection.JoinGame();
}

As an added benefit, you don't need special handling for WebGL and nothing blocks unless it should

support for received messages?

Hello, I'm able to connect, disconnect and send messages but is there any support for receiving messages from another client?

Messages being dropped

Hello,

Is there a way to fix or reduce the number of messages being dropped when lots of messages are being received on the client.

Thank you in advance.

Building for Android: error: dlopen failed: library "advapi32" not found"

Received this error in a large project when building for Android. To test I made a fresh project with only NativeWebSocket and a Connection demo script.

Built for Android in Unity 2019.3.1f1 I am getting the following error:

Plugins: Couldn't open advapi32, error: dlopen failed: library "advapi32" not found

This error prints twice and then the project runs normally.
It doesn't seem to affect the library from running as expected.

Error! The remote party closed the WebSocket connection without completing the close handshake.

Hello,
I am using your code "websocket example" and i have issue it is happen in (IOS , Android ,Unity editor ) when i send 5000 messages per sec from every 4 devices i have this problem
Error! The remote party closed the WebSocket connection without completing the close handshake..

Why i do that "send 5000 message" from every mobile ? because i have game already published and there is active users between 3000 to 40000 daily and a make more test to understand why this problem i have it! because every day i have this problem and users can't play, maybe 300 to 600 can play!

In your opinion, how can I solve this problem?

More information:
Server : 32 Core / 30 GB Memory - from Google cloud .
Protocol type : TCP
Storage : 60 SSD

And thank you for plugin is very helpful.

Unable to connect to the remote server - wss

I have created a WebSocket server in NodeJs and hosted it on GCP. The URL for the server is wss://scramblegram.bluemsoftware.com

I created a client using this library

Here is my issue

If I connect to wss://scramblegram.bluemsoftware.com using this library I get "Unable to connect to the remote server"

If I connect to wss://scramblegram.bluemsoftware.com using https://www.websocket.org/echo.html it works perfectly.

If I connect to wss://echo.websocket.org using this library it works perfectly.

can someone explain what is going on and how I can debug and solve this? It makes no sense

"Unable to connect to the remote server" error when trying to connect to my websocket server

Hey! I hope this is something simple. It seems to have been a common error that spans the last decade of stack overflow, but of course a lot of them end without a solution. Just a conversation that gets about as far as I have - I can connect to the server with chrome's simple websocket server and send & receive messages, but I get the unable to connect error firing on the error callback when trying to setup a connection as shown in the readme. Here is my server and the websocket code:

https://github.com/student020341/game-server/blob/master/src/sock/eat.go#L26

I'm using the golang websocket from this package and all I can say about my understanding of that is that connections from the web browser work.

https://godoc.org/golang.org/x/net/websocket

I appreciate any suggestions, thanks! In the mean time I'm going to try a much more painful approach using System.Net.WebSockets to see if anything changes or that lets me get a more specific error message.

edit with more info:

I was able to connect to wss://echo.websocket.org with the c# client (from this project)

So... I can create a websocket from the dev tools console and connect to my server, I can connect to echo.websocket.org with this project, but I can't connect to my LAN server with this project. Hopefully that makes the problem more clear to someone :)

The url is ws://192.168.86.201:2001/sock/connect , it's a computer in my local network that is running the server in the repo I linked.

edit 2:

I was able to reproduce this with a small dotnet project that tries the connection right in main. No issues to the echo site, same error to mine. Will continue random things but that's probably the last useful tidbit I'll be able to provide. At least that rules out unity as the problem.

Win7 support?

Microsofts flavor of Websocket is known to not work at all on Win7. What about this repo? Win7 support exists?

websocket.OnOpen doesbt recognize in my IDE

Hi there thanks for this amazing package.
when I add this package in empty project it works perfectly but when I added it on my project most of the function doesn't show up in my IDE.

is there any library that may because of this or any idea about why this happened??

Serveur type

Hello, I wanted to know if it works for any type of server, such as servers created with flask?
Because on some test servers I can connect, but on mine, I can't. "Error! The WebSocket request or response contained unsupported header(s)".
While on ws://localhost:8080 or wss://demo.websocket.me/v3/channel_1?api_key=oCdCcMPQpbvNjUIzqtvF1d2X2okWpDQj4AwARJuAgtjhzKxVEjQU6IdCjwm&notify_self
I can connect.

If you have an idea you save my life!

Cannot build for WebGL when installed via UPM

Unity fails to build for WebGL with the following errors when the package was installed with UPM:
image

This does not happen when installed manually nor when building for other platforms (tested with standalone).

Is it possible to emit?

If i have

websocket.on('matchsearching',function(data){
//server side
//do something
});

in server side, can i emit in client side with this like

websocketClient.emit('matchsearching', data);
//client side

Is that possible ?

WebGL Build failed on Unity 2021.2

WebGL Build failed on Unity 2021.2

Error Log

Building Library/Bee/artifacts/WebGL/build/debug_WebGL_wasm/build.js failed with output:
/Applications/Unity/Hub/Editor/2021.2.0f1/PlaybackEngines/WebGLSupport/BuildTools/Emscripten/emscripten/tools/acorn-optimizer.js:1845
  throw err;
  ^

SyntaxError: Unexpected token (3707:62)
  var textEncoder={encoding:"utf-8",encode:encode(input = '') {
                                                              ^

    at Parser.pp$4.raise (/Applications/Unity/Hub/Editor/2021.2.0f1/PlaybackEngines/WebGLSupport/BuildTools/Emscripten/emscripten/node_modules/acorn/dist/acorn.js:2927:15)
    at Parser.pp.unexpected (/Applications/Unity/Hub/Editor/2021.2.0f1/PlaybackEngines/WebGLSupport/BuildTools/Emscripten/emscripten/node_modules/acorn/dist/acorn.js:698:10)
    at Parser.pp.expect (/Applications/Unity/Hub/Editor/2021.2.0f1/PlaybackEngines/WebGLSupport/BuildTools/Emscripten/emscripten/node_modules/acorn/dist/acorn.js:692:28)
    at Parser.pp$3.parseObj (/Applications/Unity/Hub/Editor/2021.2.0f1/PlaybackEngines/WebGLSupport/BuildTools/Emscripten/emscripten/node_modules/acorn/dist/acorn.js:2563:14)
    at Parser.pp$3.parseExprAtom (/Applications/Unity/Hub/Editor/2021.2.0f1/PlaybackEngines/WebGLSupport/BuildTools/Emscripten/emscripten/node_modules/acorn/dist/acorn.js:2302:19)
    at Parser.pp$3.parseExprSubscripts (/Applications/Unity/Hub/Editor/2021.2.0f1/PlaybackEngines/WebGLSupport/BuildTools/Emscripten/emscripten/node_modules/acorn/dist/acorn.js:2129:21)
    at Parser.pp$3.parseMaybeUnary (/Applications/Unity/Hub/Editor/2021.2.0f1/PlaybackEngines/WebGLSupport/BuildTools/Emscripten/emscripten/node_modules/acorn/dist/acorn.js:2106:19)
    at Parser.pp$3.parseExprOps (/Applications/Unity/Hub/Editor/2021.2.0f1/PlaybackEngines/WebGLSupport/BuildTools/Emscripten/emscripten/node_modules/acorn/dist/acorn.js:2041:21)
    at Parser.pp$3.parseMaybeConditional (/Applications/Unity/Hub/Editor/2021.2.0f1/PlaybackEngines/WebGLSupport/BuildTools/Emscripten/emscripten/node_modules/acorn/dist/acorn.js:2024:21)
    at Parser.pp$3.parseMaybeAssign (/Applications/Unity/Hub/Editor/2021.2.0f1/PlaybackEngines/WebGLSupport/BuildTools/Emscripten/emscripten/node_modules/acorn/dist/acorn.js:1997:21) {
  pos: 137841,
  loc: Position { line: 3707, column: 62 },
  raisedAt: 137842
}
emcc2: error: '/Applications/Unity/Hub/Editor/2021.2.0f1/PlaybackEngines/WebGLSupport/BuildTools/Emscripten/node/node /Applications/Unity/Hub/Editor/2021.2.0f1/PlaybackEngines/WebGLSupport/BuildTools/Emscripten/emscripten/tools/acorn-optimizer.js /var/folders/lf/dlnxxblj6113m9w7r2tw1p2r0000gn/T/emscripten_temp_o2qwpj5n/build.js.pp.js AJSDCE minifyWhitespace' failed (1)
UnityEditor.BuildPlayerWindow:BuildPlayerAndRun () (at /Users/bokken/buildslave/unity/build/Editor/Mono/BuildPlayerWindow.cs:179)

Is support for WebGL builds approved/condoned by Unity?

Hello,

I'm thinking about using this for a game I'm developing, and wanted to know if support for WebGL is stable. Reading the Unity documentation, I see:

WebGL does not allow direct access to IP Sockets, but you can use WebSockets or WebRTC (the two most common networking protocols supported by browsers) to get around this. While WebSockets are widely supported, WebRTC allows peer-to-peer connections between browsers and unreliable connections. Unity does not have a built-in API that allows you to use WebSockets or WebRTC, but you can use a JavaScript plugin to implement this

https://docs.unity3d.com/Manual/webgl-networking.html

Maybe I'm misreading this message, but it sounds like the last sentence implies that C# binaries built with Unity have no way of creating websocket connections unless you create one from javascript and then tunnel your socket connection through javascript. I looked at this repository and I don't see you doing this, so how exactly does support for WebGL work here? It seems to use System.Net.Websockets, but I'm not convinced that this is in agreement with the Unity doc I linked above.

Is System.Net.Websockets deprecated in WebGL builds for new versions of Unity? Is there something I've missed?

PS sorry if I've placed this in the wrong spot and been a bother. If there's a better place to followup with this, close the issue and let me know where to post instead.

Connect to server built with flask-socketio

Hi there,

Sorry that this question might be stupid but I just started to get in touch with all the networking stuff. I'm wondering if it's possible to use this package to connect to a server built with flask-socketio.

I was testing on my mac and I picked localhost:8765 on the server side and tried to connect it with websocket = new WebSocket("ws://localhost:8765"); but it reported an error:

Error! Unable to connect to the remote server
UnityEngine.Debug:Log(Object)
<>c:b__1_1(String) (at Assets/Scripts/util/Connection.cs:27)
NativeWebSocket.d__26:MoveNext() (at Library/PackageCache/com.endel.nativewebsocket@90f55f370a/WebSocket/WebSocket.cs:477)
UnityEngine.UnitySynchronizationContext:ExecuteTasks() (at /Users/bokken/buildslave/unity/build/Runtime/Export/Scripting/UnitySynchronizationContext.cs:107)

Thanks in advance!

Cannot send text in OnOpen() event method

Thank you for providing this easy to use web socket library. Recently I got an issue that I used SendText() method in OnOpen() event method, but the text message didn't sent i.e. server didn't receive the text message. I use AWS API Gateway WebSocket service. Please help to solve this issue. Thank you.

IL2CPP Support

I am utilizing another plugin called Agora which requires IL2CPP. I am using this plugin as my websocket library but when compiling to IL2CPP I set silent errors and messages aren't send on ws.send. There is a connection established but no outgoing messages.

I confirmed this is related to IL2CPP because you attach a debugger IL2CPP is everywhere with issues, and when in Mono everything works fine.

Is there an approach for modifying for IL2CPP support?

Connect() is not the same on WebGL as on other builds

I'm not sure if this is by design, or an issue, but on non-WebGL builds, await websocket.Connect() will return when the socket is open (or failed, I suppose).

On WebGL however, as Connect() returns Task.CompletedTask immediately, this isn't the case, and if you have this in a "synchronous" context, the socket isn't actually available. You need to loop and wait until OnOpen is called.

So this code:

await websocket.Connect();
await websocket.SendText("hello");

doesn't work on WebGL. You need to do something like:

await websocket.Connect();

// await wrapper around coroutine call with something like Unity3dAsyncAwaitUtil
await new WaitUntil( () => websocket.State == WebSocketState.Open );

await websocket.SendText("hello");

Question about example

The example has the following code:

  void Update()
  {
    #if !UNITY_WEBGL || UNITY_EDITOR
      websocket.DispatchMessageQueue();
    #endif
  }

I was looking over the #define directives and it looks like to me, the second part of this, UNITY_EDITOR, will never be evaluated.

Ability to determine if a message is binary or text

Currently, the API only has OnMessage(byte[] bytes), but this doesn't allow us to determine if the message was encoded as binary or text. This data is known to the library via WebSocketMessageType, so I suggest this be exposed to clients as well.

Some options:

  1. Add a second parameter, like: OnMessage(byte[] bytes, WebSocketMessageType messageType)
  2. Create separate events, like: OnMessageText(string data) and OnMessageBinary(byte[] bytes).

I'd be happy to submit a PR implementing either approach, let me know what you think!

Thanks again for this great library.

Issue after uploading to s3

Hi I have tested in unity it is working fine but after uploading to s3 it is showing the below error.
Uncaught SecurityError: Failed to construct 'WebSocket': An insecure WebSocket connection may not be initiated from a page loaded over HTTPS.

Cannot reconnect a WebSocket in WebGL

The sequence...

  • Opening a socket: Invoke() on a method calling await _webSock.Connect();
  • Sending messages: Calling _webSock.SendText(msg);
  • Closing the socket: Invoke() on a method calling await _webSock.Close();

Everything works fine.
All the calls are performed inside the Update() method.
The three calls are user-controlled. Hence, some seconds pass between them.

Now, trying to re-open the socket again with: Invoke() on a method calling await _webSock.Connect();
Work good in Unity Editor.
Fails in WebGL with error:

WebSocketInvalidStateException: WebSocket is already connected or in connecting state.
  at NativeWebSocket.WebSocket.Connect () [0x00000] in <00000000000000000000000000000000>:0 
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x00000] in <00000000000000000000000000000000>:0 
 
(Filename: currently not available on il2cpp Line: -1)

How can I use it in Unity 2018.1.4f1

When I opened your demo in Unity 2020, I exported a Unity package aiming to use it in Unity 2018, but I encountered incompatibility problems, detail is shown on screenshot below. I know that you have noted in README file about the compatibility problem, but I am hoping to use one just like yours in 2018 version of Unity. May you gitve me some advice? Or may you make it open source and compatible with 2018 version?

图片




Plus, a very funny thing in your demo is that you added RigidBody component onto Camera, camera will be falling down once the scene is played.
图片

Why close connection once message is sent?

In Websocket.SendMessage we have:

var t = m_Socket.SendAsync(buffer, messageType, true, m_CancellationToken);

Because the third argument is true, this websocket client closes connection actively after message is sent.

What is the reason behind this design decision? In most use cases of websocket, I want a ongoing stream where I can repeatedly put my messages into, If I want the connection to be closed as soon as I get the message out, I would use http instead.

websocket.OnMessage never called in the demo (same in my project)

Hello, first of all thank you for your work on this websocket implementation :)
I have a question, and maybe a bug.

First I start the node server script in a terminal (on localhost)
Then I start the demo scene from this repository (master branch) in unity mac 2019.3.7.f1

✅ The node server receive all the unity messages:

$ node index.js 
Listening on http://localhost:8080
client joined.
client sent a message: <Buffer 0a 14 1e>
client sent a message: plain text message
client sent a message: <Buffer 0a 14 1e>
client sent a message: plain text message
client sent a message: <Buffer 0a 14 1e>
client sent a message: plain text message
...

but on the Unity side I don't get the message from the server (as I understand in the code, the server is sending messages too)
var id = setInterval(() => ws.send("hello world!"), 100); (note it should probably be 1000 instead of 100 but it's a detail

❌ In Unity console I only get:

Connection open!

and that's it.

Firewalls are off, everything is open.

I guess there is something wrong here?
Any idea?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.