Unity & NodeJS
Published in

Unity & NodeJS

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

WebSocket Client & Server (Unity & NodeJS)

Creating a NodeJS WebSocket server and Unity C# WebSocket Client

NodeJS WebSocket Server

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

Websocket Server Module events
WebSocket Server Module events
WebSocket Client Module events
WebSocket Client Module events
View in the VS Code Terminal
View in the VS Code Terminal

WebSocket Client in Unity (C#)

WebSocket C# for Unity using Nuget PackageManager
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

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");
}
}
}
Message sent from Unity client to NodeJS server and NodeJS server forward the message back to Unity client

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store