Code Monkey home page Code Monkey logo

unity-websocket-webgl's Introduction

unity-websocket-webgl

Maintainers Wanted

I've created this library as a Hobby project when I was experimenting with Unity. I haven't used Unity for over 2 years and I'm not able to maintain the repo. If you want to become a maintainer a keep this project running, send me an e-mail or create an issue. Thank you for understanding.


Hybrid event-driven WebSocket implementation for Unity 3D.

It automatically compiles browser or native implementation based on project's target platform. Native implementation is using WebSocketSharp library (must be downloaded separately - see below). For the browser implementation the custom emscripten JSLIB is used.

Warning: WebSocket client is intended to support only binary messages. So if you want to send or receive string messages you must convert it to/from byte array in your code.

Downloading WebSocketSharp

You can get WebSocketSharp.dll from NuGet package manager. See NuGet Gallery: websocket-sharp.

Library can be installed manually. Just download the NuGet package. Then rename the file extension from .nupkg to .zip and extract it. Now you can copy lib/websocket-sharp.dll file to your Unity project into the Assets/Plugins directory.

For more info please visit official WebSocketSharp GitHub repo.

Installing plugin

To install this plugin just copy the contents of Plugins directory to your Unity project's Assets/Plugins directory.

Usage

For example usage see Scripts/WebSocketDemo.cs file. You can import it to your project and assign it to any GameObject. Then run your project and check the console.

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

// Use plugin namespace
using HybridWebSocket;

public class WebSocketDemo : MonoBehaviour {

    // Use this for initialization
    void Start () {

        // Create WebSocket instance
        WebSocket ws = WebSocketFactory.CreateInstance("ws://echo.websocket.org");

        // Add OnOpen event listener
        ws.OnOpen += () =>
        {
            Debug.Log("WS connected!");
            Debug.Log("WS state: " + ws.GetState().ToString());

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

        // Add OnMessage event listener
        ws.OnMessage += (byte[] msg) =>
        {
            Debug.Log("WS received message: " + Encoding.UTF8.GetString(msg));

            ws.Close();
        };

        // Add OnError event listener
        ws.OnError += (string errMsg) =>
        {
            Debug.Log("WS error: " + errMsg);
        };

        // Add OnClose event listener
        ws.OnClose += (WebSocketCloseCode code) =>
        {
            Debug.Log("WS closed with code: " + code.ToString());
        };

        // Connect to the server
        ws.Connect();

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

Error Handling

When any error occours during method call then the WebSocketException is thrown. Unified both for native and browser client so you can catch it in your C# code.

License Apache 2.0

Copyright 2018 Jiri Hybek [email protected]

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

unity-websocket-webgl's People

Contributors

eri24816 avatar jirihybek avatar tylerstein 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

unity-websocket-webgl's Issues

Encountering Error in WebSocketConnect

I'm not sure why but when I call WebSocketConnect from C# side in the WebGL build it fails. Most relevant stack:

uncaught exception: abort("To use dlopen, you need to use Emscripten's linking support, see https://github.com/kripken/emscripten/wiki/Linking") at jsStackTrace (WebGL.wasm.framework.unityweb:8:22325) stackTrace (WebGL.wasm.framework.unityweb:8:22496) onAbort@file:///C:/Users/Glader/Documents/Unity%20Projects/Rs317.Unity.WebGL/Build/WebGL/Build/UnityLoader.js:4:11047 abort (WebGL.wasm.framework.unityweb:8:490242) _dlopen (WebGL.wasm.framework.unityweb:8:177090)
...
dynCall (WebGL.wasm.framework.unityweb:8:15172) _WebSocketConnect [_WebSocketConnect/instance.ws.onmessage] (WebGL.wasm.framework.unityweb:8:58056)

Doesn't work on Browser but works on Unity?

Tried to write a simple demo (source here) with this library, when started with Unity it works fine, but when built to HTML5 target (warning, development build is 33MB) (either development or release version/9MB), it doesn't show up correctly, server sends correct values, but the client doesn't handle the message from server when running on Browser.

Any way how to find out what's wrong?

Reproduce steps:

  1. clone the project
  2. run on Unity (2018.x)
  3. Build > HTML5
  4. upload to certain server (or use the link above)

Can't handshake with WSS

Error log:

WS closed with code: TlsHandshakeFailure
UnityEngine.Debug:Log(Object)
<>c:<Start>b__1_2(WebSocketCloseCode) (at Assets/Scripts/WebSocketDemo.cs:40)
HybridWebSocket.WebSocket:<.ctor>b__13_3(Object, CloseEventArgs) (at Assets/Plugins/WebSocket.cs:495)
WebSocketSharp.Ext:Emit(EventHandler`1, Object, CloseEventArgs) (at E:/Repos/WebsocketsSharp/websocket-sharp/Ext.cs:1269)

In sta/websocket-sharp, this is fixed by adding this line:
ws.SslConfiguration.EnabledSslProtocols = System.Security.Authentication.SslProtocols.Tls12;

Is it possible to fix this in this library? I could add this line myself in the constructor, I'm just not sure what's the correct way to treat it.

Free allocated memory in JSLIB

Free allocated memory for messages passed to callbacks after they are called to prevent memory leaks.

Also, put Runtime.DynCall into try/catch/finally statements to free memory in any situation.

TextMeshPro not updated when using Websocket's callback?

I'm using Unity 2018.2, it's weird to see that the property on editor is correct but textmeshpro not updated only when using websocket's callback (normal event works, ain't working only when using websocket's callback)

minimum code to reproduce

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using HybridWebSocket;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class Main : MonoBehaviour 
{

    public Button sendButton;
    public TextMeshProUGUI chatLabel;
    public TMP_InputField chatInput;

    WebSocket ws;

    void Start()
    {
        ws = WebSocketFactory.CreateInstance("ws://echo.websocket.org");
        ws.OnOpen += websocket_Opened;
        ws.OnError += websocket_Error;
        ws.OnClose += websocket_Closed;
        ws.OnMessage += websocket_MessageReceived;
        ws.Connect();

        sendButton.onClick.AddListener(delegate ()
        {
            AppendText("sending: " + chatInput.text);
            ws.Send(Encoding.UTF8.GetBytes(chatInput.text));
        });
    }

    private void websocket_Error(string errormsg)
    {
        throw new NotImplementedException();
    }

    private void websocket_MessageReceived(byte[] data)
    {
        AppendText("from server: " + Encoding.UTF8.GetString(data));
    }

    private void websocket_Closed(WebSocketCloseCode closeCode)
    {
        AppendText("Websocket closed: " + closeCode);
    }

    private void websocket_Error(object sender, EventArgs e)
    {
        AppendText("Websocket error: " + e);
    }

    private void AppendText(string str)
    {
        Debug.Log(str);
        chatLabel.text += str + "\n";
    }

    private void websocket_Opened()
    {
        AppendText("Websocket opened.. ");
    }
}

Missing byte in allocated string in instance.ws.onerror

var msg = "WebSocket error.";
var msgBytes = lengthBytesUTF8(msg);
var msgBuffer = _malloc(msgBytes + 1);
stringToUTF8(msg, msgBuffer, msgBytes);

should be

var msg = "WebSocket error.";
var msgBytes = lengthBytesUTF8(msg) + 1;
var msgBuffer = _malloc(msgBytes);
stringToUTF8(msg, msgBuffer, msgBytes);

Cant receive any response from server in Build version

Everything is working great on the Build version except the OnMessage trigger.

It shows the log when connection is established, and my server can read the message sent from it. Only when I responded from my server side by sending or by broadcasting message, it triggered OnMessage the client that was running on my Unity Game Player but it never triggered the OnMessage on my build.

I'm using the build and run option on unity, so the build is running on localhost & as for the backend it's running on a remote server

Uncaught exception when WebSocketSend called after WS closed

An uncaught exception will occur if WebSocketSend is called after the ws property on the instance has already been deleted here: https://github.com/jirihybek/unity-websocket-webgl/blob/master/Plugins/WebSocket.jslib#L205

Uncaught TypeError: Cannot read property 'readyState' of undefined

This is because the WebSocketSend method only checks for null, but in this case the value would be undefined here: https://github.com/jirihybek/unity-websocket-webgl/blob/master/Plugins/WebSocket.jslib#L258

I will have a PR with the fix momentarily.

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.