Websocket Sharp Unity Server

public class Echo : WebSocketBehavior
{

    private static NetworkingStuff Jsonstuff;

    protected override void OnMessage(MessageEventArgs e)
    {


    }

}


public class Networking_MainNetworking : MonoBehaviour
{

    private static NetworkingStuff Jsonstuff;
    private GameObject Player;
    private Rigidbody PlayerRigidBody;
    private Echo wssv;


 
    void Start()
    {

        var wssv = new WebSocketServer(8765);
        wssv.AddWebSocketService<Echo>("/Echo");
        wssv.Start();
        Application.targetFrameRate = 60;


    }

I need to be able to retrieve messages in onmessage (which works), and process their inputs with the unity API, however, the messages are retrieved on new threads, and I have no idea how to use them with unity’s main thread

1 Like

My favorite way to transfer data back to Unity’s main thread is like this:

using System.Collections.Concurrent;
using UnityEngine;

public class MyClass : MonoBehaviour {
  ConcurrentQueue<string> queue = new ConcurrentQueue<string>();

  void Update() {
    while (queue.TryDequeue(out string message)) {
      print ("Received message: " + message);
    }
  }

  public void SendMessageFromAnotherThread(string message) {
    queue.Enqueue(message);
  }
}

Then you just call SendMessageFromAnotherThread() with your message (from the other thread), and this MonoBehaviour will be able to process it on the main thread. Of course, you don’t have to use string, that’s just for illustration purposes. Just be careful that whatever object you use is either thread safe or not being used by the other thread anymore.

2 Likes

Trying that now

I’m really bad with classes. How exactly would I call that method, from outside of the monobehaviour inherited class? (MyClass)

@PraetorBlue This was simple and helped me fix my problem thank you!
@allencook200
SendMessageFromAnotherThread needs to be defined with OnMessage method.

The Queue can either:

  1. Be defined with your Echo class and then referenced with your MonoBehavior like wssv.queue or
  2. Define the Queue within your MonoBehavior and pass it into your Echo class in some way.

I am not as good with C# as I am with other languages so my syntax may not be 100% correct but theoretically you should be able to pass in these objects between classes.

For me have have my webSocket definitions within my MonoBehavior, so everything is in one class and I was able to add the methods Praetor mentioned to it with no problem. Hope this helps!

You’re replying to a 2 1/2 month old thread.

If you’re writing an app that DOESN’T run in the browser, I would highly recommend ditching websockets and using C#'s built-in UDP/TCP sockets and not shitty old websockets.