How to use socket.io in Unity WebGL

Overview

Setup Socket Client for Unity WebGL

This is simply a guide with some code samples to get you started and is NOT a Unity package/plugin that you can import into your Unity package.

If you are looking to use sockets in Unity then be warned that:

WebGL doesn’t 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 doesn’t have a built-in API that allows you to use WebSockets or WebRTC, but you can use a JavaScript plugin to implement this. Source: Unity Docs

The solution is to use create your own browser script to interact with sockets.

Setup

To make the browser script run as expected you will need to install socket and make the Unity instance accessible. But you can only do this once you have build the project to WebGL. After building, navigate to the index.html file at the root of the built project. If you build your project in a different folder, you will have to do this setup again.

Socket Installation

Add a script to import socket.io (or other websocket libraries that you used in your browser script).

I reccommend using a CDN instead of a local file for convenience. This is the example for importing Socket.io 4.0.0 (this is not the latest version, you can import any version).

<script src="https://cdn.socket.io/4.0.0/socket.io.js"></script>

Unity Browser Instance

You will need to add some lines of code to facilitate sending data back to your C# script:

Find the script tag that is inside the body element and insert the two labelled statements below

<script>
    ...

    function unityShowBanner(msg, type) {
        ...
    } 

    var unityInstance; // <--- Add this statement
    var buildUrl = "Build";
    var loaderUrl = buildUrl + "/webbuild.loader.js";

    ...

    script.onload = () => {
        createUnityInstance(canvas, config, (progress) => {
          progressBarFull.style.width = 100 * progress + "%";
        }).then((unityInstance) => {
          this.unityInstance = unityInstance; // <--- Add this statement
          loadingBar.style.display = "none";
          fullscreenButton.onclick = () => {
            unityInstance.SetFullscreen(1);
          };
        }).catch((message) => {
          alert(message);
        });
      };
      document.body.appendChild(script);
</script>

Credit to KyleDulce for this.

Browser Script

  1. Create a 'Plugins' folder in your Unity Assets directory if it is not already there.
  2. Create a new file called socket_client.jslib (you can name this file whatever you want as long as it has the suffix .jslib). Make sure to create this file in the Plugins folder or any subfolder. This .jslib file is your browser script.
  3. Copy text from the socket.jslib file into socket_client.jslib.
  4. Modify the contents of your script according to your needs. Consult relevant Unity Scripting Docs and SocketIO Docs.

Communication between C# and JS

The Unity Docs on this are easy to understand and to the point and I would reccommend you check it out for more details here.

In your C# script add this import:

using System.Runtime.InteropServices;

and then add these two lines for every function you want to import from your browser script and wrap it in a directive so that it only runs when you are in the WebGL platform:

#if UNITY_WEBGL
    [DllImport("__Internal")]
    private static extern void YourFunction();
#endif

You must also define function arguments due to C# being strongly typed:

[DllImport("__Internal")]
private static extern void YourFunctionWithArgs(string str, int num);

To send data from your browser script to your C# script, use:

window.unityInstance.SendMessage('MyGameObject', 'MyFunction', 'MyArgument');

For this to work make sure you follow the isntructions in the setup.

You might also like...

Örnek kurye takip socket uygulaması

Örnek kurye takip socket uygulaması

Kullanılan Teknolojiler NodeJS npm Bilgi Proje 4646 portunda çalışmaktadır. Dilerseniz bu portu değiştirebilirsiniz. server.listen(4646, function () {

Nov 27, 2022

curtains.js is a lightweight vanilla WebGL javascript library that turns HTML DOM elements into interactive textured planes.

curtains.js is a lightweight vanilla WebGL javascript library that turns HTML DOM elements into interactive textured planes.

What is it ? Shaders are the new front-end web developpment big thing, with the ability to create very powerful 3D interactions and animations. A lot

Jan 1, 2023

[WIP] WebGL API implementation for Deno, built on GLFW using FFI.

Note I'm no longer working on this project because I have just realized macOS does not support OpenGL ES API, and adding Desktop GL backend to this mo

Jun 11, 2022

WebGL and GLSL projects 2022 🌬

Getting Started Node version used : 16.13.1 First install dependencies with: npm install # or yarn install Then, run the development server: npm run d

Dec 23, 2022

Space Invaders in your browser with 3D WebGL. Built with BabylonJS.

Space Invaders in your browser with 3D WebGL. Built with BabylonJS.

Space Invaders A fun re-imagining of the 1978 classic by Tomohiro Nishikado and Taito. Play it here: https://spaceinvaders.viperfish.com.au Play in th

Dec 26, 2022

This project is an attempt at recreating the WebGL animation featured in the 2021 Linear release page.

Linear Vaporwave Three.js scene This project is an attempt at recreating the WebGL animation featured in the 2021 Linear release page. Demo Head over

Dec 28, 2022

All-in-one package for maptalks webgl layers

@maptalks/gl-layers maptalks webgl 图层的汇总包,包含了@maptalks命名空间下webgl基础设施和所有webgl图层插件。 使用时无需再单独安装和引入其他webgl插件,而可以统一从此包中安装引用。 包含的插件 @maptalks/gl @maptalks/v

Dec 23, 2022

Phaser is a fun, free and fast 2D game framework for making HTML5 games for desktop and mobile web browsers, supporting Canvas and WebGL rendering.

Phaser is a fun, free and fast 2D game framework for making HTML5 games for desktop and mobile web browsers, supporting Canvas and WebGL rendering.

Phaser - HTML5 Game Framework Phaser is a fast, free, and fun open source HTML5 game framework that offers WebGL and Canvas rendering across desktop a

Jan 7, 2023

A devtool improve your pakage manager use experience no more care about what package manager is this repo use; one line, try all.

pi A devtool improve your pakage manager use experience no more care about what package manager is this repo use; one line, try all. Stargazers over t

Nov 1, 2022
Owner
Jatin Mehta
Full Stack Developer (Web, Mobile)
Jatin Mehta
I built a full-stack project using Node, Express, Mongo, webRTC, socket.io, and of course React JS. This project is inspired by the awesome Clubhouse 😊

codershouse-mern - This Project is Under Development. Below are some of the implemented interface and the remaining features will be updated in future

Bishal Das 35 Nov 18, 2022
A social network app cloned from Instagram built with Next.Js, Socket.IO and a lots of other new stuff.

Instagram Noob ⚡ A social network app cloned from Instagram built with Next.Js, Socket.IO and a lots of other new stuff. Live Demo: https://instagram-

Hung Minh 20 Oct 19, 2022
Node.js implementation of the Socket SDK client

SYNOPSIS A Node.js adapter for the Socket SDK DESCRIPTION Socket SDK uses a simple uri-based protocol for brokering messages between the render proces

Socket Supply Co. 11 Dec 28, 2022
TikTokLive-Widget: A socket client/server program that exposes a widget with alerts (such as gifts, followers ...) for a specific user streaming on Tik Tok Live platform

TikTokLive-Widget: A socket client/server program that exposes a widget with alerts (such as gifts, followers ...) for a specific user streaming on Tik Tok Live platform

null 3 Dec 3, 2022
Simple google docs thing in Remix using socket.io.

This is just a simple google docs thing, me playing around with Remix and sockets. TODO: from socket.io to yjs sockets, support CRDT. Installation Aft

Tiger Abrodi 20 Apr 19, 2022
a chatt app build using node , express and socket IO , it has many rooms

RealTime-chatt-app you can view the app here : https://bit.ly/3zce4ON a chatt app build using node , express and socket IO . used to public chatt room

null 11 Aug 31, 2022
A complete application tutorial to show how to implement the Web Socket protocol using only Node.js builtin modules

Web Socket application using only Node.js built-in modules About Welcome, this repo is part of my youtube video about Building a complete application

Erick Wendel 35 Dec 19, 2022
A chat application made using Next.js and Socket.io.

Chat App Login Page Create Room Default Room Protected Room Demo Getting Started ?? Development Server npm install --s --f && npm run dev # or yarn in

null 12 Dec 28, 2022
Socket.IO server for Deno

Socket.IO server for Deno An implementation of the Socket.IO protocol for Deno. Table of content: Usage Options path connectTimeout pingTimeout pingIn

Socket.IO 53 Jan 1, 2023
Socket IO Connector for Yjs (Inspired by y-websocket)

Welcome to y-socket.io ?? Socket IO Connector for Yjs (Inspired by y-websocket) Y-socket.io is a YJS document synchronization implementation over the

Iván Topp Sandoval 18 Dec 21, 2022