WebSocket Server and Client using NodeJS & Unity
WebSocket Server and Client using NodeJS & Unity

WebSocket Client & Server (Unity & NodeJS)

Ahmed Schrute
Unity & NodeJS
Published in
4 min readDec 7, 2020

--

In this tutorial we will create a NodeJS WebSocket server and a Unity C# client and will communicate messages between the server and the client.

Creating a NodeJS WebSocket server and Unity C# WebSocket Client

NodeJS WebSocket Server

Here is the NodeJS Websocket server example:

const WebSocket = require('ws')const wss = new WebSocket.Server({ port: 8080 },()=>{    console.log('server started')})wss.on('connection', function connection(ws) {   ws.on('message', (data) => {      console.log('data received \n %o',data)      ws.send(data);   })})wss.on('listening',()=>{   console.log('listening on 8080')})

Server Code Explanation

We are using ws module from to create the websocket server

The websocket socket server have 5 events we can listen to and trigger whatever actions we want, you can find the docs for these events here.

Websocket Server Module events
WebSocket Server Module events

First we created the server and listen to messages on port 8080 and we print small message “server started”

Second, we listen to the WebSocket server module events, we are using listening to 2 events listening and connection .

Once we start listening to the connection event we can capture the connected client and start listening to the client events.

the WebSocket Client module have 8 events that we can listen to, you can find the docs of the WebSocket client events here

WebSocket Client Module events
WebSocket Client Module events

Once we capture the connected client we listen to ‘message’ event on the client and collect the data sent from the client and simply send it back to the same client.

You should be seeing the following in the terminal when you start your server

View in the VS Code Terminal
View in the VS Code Terminal

WebSocket Client in Unity (C#)

To get started with WebSocket client in Unity we will use Nuget the C# package manager to add a WebSocket C# library.

You can download the Nuget Unity plugin from here

Once you imported the Nuget Unity package to your project, you can search for “WebSocketSharp-netstandard” and install to the Unity Project.

WebSocket C# for Unity using Nuget PackageManager

Here is the Unity C# WebSocket Client example:

using UnityEngine;
using WebSocketSharp;
public class WsClient : MonoBehaviour
{
WebSocket ws;
private void Start()
{
ws = new WebSocket("ws://localhost:8080");
ws.Connect();
ws.OnMessage += (sender, e) =>
{
Debug.Log("Message Received from "+((WebSocket)sender).Url+", Data : "+e.Data);
};
}
private void Update()
{
if(ws == null)
{
return;
}
if (Input.GetKeyDown(KeyCode.Space))
{
ws.Send("Hello");
}
}
}

Client Code Explanation

We are using two namespaces “UnityEngine” so we can use Monobehaviour to use Start & Update callbacks, and we are using “WebSocketSharp” to use the WebSocket client implementation.

In the Start function we assign a new WebSocket object with the WebSocket url to the ws WebSocket object.

ws = new WebSocket("ws://localhost:8080");

Then we start the WebSocket connection

ws.Connect();

Afterwards we add a listener to onMessage to print out the sender url and the data received from the sender.

ws.OnMessage += (sender, e) =>
{
Debug.Log("Message Received from "+((WebSocket)sender).Url+", Data : "+e.Data);
};

In the Update callback, we check that the websocket started if not we return.

We send a message to the server if the Space Button was pressed.

private void Update()
{
if(ws == null)
{
return;
}
if (Input.GetKeyDown(KeyCode.Space))
{
ws.Send("Hello");
}
}
}

Once you run the scene in the editor & the server is running you should see the following in Unity & NodeJS server

Message sent from Unity client to NodeJS server and NodeJS server forward the message back to Unity client

--

--