SocketIOUnity Documentation

repository·main·Indexed 19 days ago

https://github.com/itisnajim/socketiounity

A Unity wrapper for the socket.io-client-csharp library that enables integration with Socket.IO v2, v3, and v4 servers. It supports WebSocket and HTTP polling transports, provides options for JSON serialization via System.Text.Json or Newtonsoft Json.NET, and includes mechanisms to handle Unity main thread execution for event callbacks.

Tokens
1.1K
Snippets
6
Records
6
Agent score
18%

What's inside SocketIOUnity

  1. Install SocketIOUnity via Unity Package Manager

    main

    To install SocketIOUnity in your Unity project, use the Git URL method in the Package Manager:

    1. Copy the following URL: https://github.com/itisnajim/SocketIOUnity.git
    2. In Unity, open Window -> Package Manager.
    3. Click the (+) button and select Add package from git URL....
    4. Paste the URL and click Add.
    https://github.com/itisnajim/SocketIOUnity.git
  2. Receive events and handle Unity Threading

    main

    When receiving events via socket.On, the callback may run on a background thread. If you need to interact with Unity objects (e.g., transforming a GameObject) or use PlayerPrefs, you must ensure the code runs on the Unity main thread.

    Option 1: Using unityThreadScope and OnUnityThread

    Set the unityThreadScope property to one of the following: .Update, .LateUpdate, or .FixedUpdate (default is .Update). Then use OnUnityThread instead of On.

    Option 2: Using UnityThread.executeIn...

    Inside a standard socket.On callback, wrap your Unity-specific logic in UnityThread.executeInUpdate, UnityThread.executeInLateUpdate, or UnityThread.executeInFixedUpdate.

    // Option 1: Setting thread scope
    socket.unityThreadScope = UnityThreadScope.Update; 
    socket.OnUnityThread("spin", (response) => {
        objectToSpin.transform.Rotate(0, 45, 0);
    });
    
    // Option 2: Manual execution in Update
    socket.On("spin", (response) => {
        UnityThread.executeInUpdate(() => {
            objectToSpin.transform.Rotate(0, 45, 0);
        });
    });
  3. Initialize a SocketIOUnity instance

    main

    To start using the library, create a new SocketIOUnity instance with a URI and optional SocketIOOptions.

    Note: To prevent the socket from being destroyed when changing scenes, consider placing the script on a Camera object or using DontDestroyOnLoad.

    var uri = new Uri("https://www.example.com");
    socket = new SocketIOUnity(uri, new SocketIOOptions
    {
        Query = new Dictionary<string, string>
            {
                {"token", "UNITY" }
            }
        , 
        Transport = SocketIOClient.Transport.TransportProtocol.WebSocket
    });
  4. Emit events from SocketIOUnity

    main

    You can send data to the server using several Emit methods. This includes simple event names, strings, objects, or asynchronous calls.

    socket.Emit("eventName");
    socket.Emit("eventName", "Hello World");
    socket.Emit("eventName", someObject);
    
    // Emit with a callback response
    socket.Emit("eventName", (response) => {
        string text = response.GetValue<string>();
        print(text);
    }, someObject);
    
    // Emit a raw JSON string
    socket.EmitStringAsJSON("eventName", "{\"foo\": \"bar\"}");
    
    // Asynchronous emit (requires the method to be async)
    await client.EmitAsync("hi", "socket.io");
  5. Connect and Disconnect the socket

    main

    Use either synchronous or asynchronous methods to manage the connection state.

    // Synchronous
    socket.Connect();
    socket.Disconnect();
    
    // Asynchronous
    await socket.ConnectAsync();
    await socket.DisconnectAsync();
  6. Configure the JSON Serializer

    main

    By default, the library uses System.Text.Json. However, if you are using IL2CPP and encounter issues, you can switch to Newtonsoft Json.NET by assigning a NewtonsoftJsonSerializer to the JsonSerializer property.

    socket.JsonSerializer = new NewtonsoftJsonSerializer();