DEV Community

Cover image for How to Implement Socket Communication in Unreal Engine and Node.js
Imai Jiro
Imai Jiro

Posted on

How to Implement Socket Communication in Unreal Engine and Node.js

In this tutorial, we'll explore how to implement socket communication between a Node.js server and both Unreal Engine 5 (UE5) and Unity using WebSockets. While both Unreal Engine and Unity are excellent platforms for creating real-time applications, they each have unique ways of handling socket communication. Think of Unreal Engine as a teacher that encourages a more high-fidelity, visually immersive approach, while Unity tends to be a bit more straightforward and accessible for rapid development.

Let’s dive into how you can set up socket communication in both engines and see how their unique teaching styles come into play.

Prerequisites

Before we begin, ensure you have the following installed:

  • Node.js and npm:Install Node.js

  • Unreal Engine 5 (UE5)

  • Unity (for comparison)

  • Visual Studio (for Unreal Engine development)

1. Setting Up the Node.js WebSocket Server

Let's first create a simple WebSocket server using ws, a popular WebSocket library for Node.js. This will act as our "teacher" in this analogy, delivering lessons (messages) to both Unreal Engine and Unity students.

Install the ws library:

npm init -y
npm install ws
Enter fullscreen mode Exit fullscreen mode

Create the WebSocket server (server.js):

const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', ws => {
  console.log('New connection established');

  ws.on('message', message => {
    console.log(`Received message: ${message}`);
    // Send back a response to the client
    ws.send('Message received by Node.js server!');
  });

  ws.on('close', () => {
    console.log('Connection closed');
  });
});

// Handle server errors
wss.on('error', err => {
  console.error('WebSocket Server Error:', err);
});

console.log('WebSocket server running on ws://localhost:8080');
Enter fullscreen mode Exit fullscreen mode

Run the WebSocket server:

node server.js
Enter fullscreen mode Exit fullscreen mode

Your server is now ready and capable of receiving and responding to messages from both Unreal Engine and Unity clients.

2. Unreal Engine 5 WebSocket Client

Now let’s look at how Unreal Engine would set up as a "student," ready to receive the lesson (messages) and act on them with its unique flair for high-quality graphics and immersive interactions.

Step 1: Enable WebSocket Support in UE5

To enable WebSocket support, add WebSockets to the PublicDependencyModuleNames in your YourProject.Build.cs:

PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "WebSockets" });

Enter fullscreen mode Exit fullscreen mode

Step 2: Create a WebSocket Client Actor in Unreal

Now, let’s create a WebSocket client in Unreal Engine that will connect to our Node.js server.

WebSocketClientActor.h:

#pragma once

#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "WebSocketsModule.h"
#include "IWebSocket.h"
#include "WebSocketClientActor.generated.h"

UCLASS()
class YOURPROJECT_API AWebSocketClientActor : public AActor
{
    GENERATED_BODY()

public:
    AWebSocketClientActor();

protected:
    virtual void BeginPlay() override;
    virtual void Tick(float DeltaTime) override;

private:
    TSharedPtr<IWebSocket> WebSocket;

    void SetupWebSocket();
    void OnWebSocketMessageReceived(const FString& Message);
};
Enter fullscreen mode Exit fullscreen mode

WebSocketClientActor.cpp:

#include "WebSocketClientActor.h"
#include "Engine/Engine.h"

AWebSocketClientActor::AWebSocketClientActor()
{
    PrimaryActorTick.bCanEverTick = true;
}

void AWebSocketClientActor::BeginPlay()
{
    Super::BeginPlay();
    SetupWebSocket();
}

void AWebSocketClientActor::SetupWebSocket()
{
    if (!FModuleManager::Get().IsModuleLoaded("WebSockets"))
    {
        FModuleManager::Get().LoadModule("WebSockets");
    }

    WebSocket = FWebSocketsModule::Get().CreateWebSocket(TEXT("ws://localhost:8080"));

    WebSocket->OnConnected().AddLambda([]()
    {
        UE_LOG(LogTemp, Log, TEXT("Successfully connected to WebSocket server"));
    });

    WebSocket->OnConnectionError().AddLambda([](const FString& Error)
    {
        UE_LOG(LogTemp, Error, TEXT("WebSocket Connection Failed: %s"), *Error);
    });

    WebSocket->OnClosed().AddLambda([](int32 StatusCode, const FString& Reason, bool bWasClean)
    {
        UE_LOG(LogTemp, Log, TEXT("WebSocket Closed: %s"), *Reason);
    });

    WebSocket->OnMessage().AddLambda([this](const FString& Message)
    {
        UE_LOG(LogTemp, Log, TEXT("Received WebSocket Message: %s"), *Message);
        OnWebSocketMessageReceived(Message);
    });

    WebSocket->Connect();
}

void AWebSocketClientActor::OnWebSocketMessageReceived(const FString& Message)
{
    if (Message.Contains("color"))
    {
        // Change the color of the actor based on the message
        UStaticMeshComponent* MeshComp = FindComponentByClass<UStaticMeshComponent>();
        if (MeshComp)
        {
            FLinearColor Color = FLinearColor::Red;
            UMaterialInstanceDynamic* DynMaterial = MeshComp->CreateAndSetMaterialInstanceDynamic(0);
            if (DynMaterial)
            {
                DynMaterial->SetVectorParameterValue(TEXT("BaseColor"), Color);
            }
        }
    }
}

void AWebSocketClientActor::Tick(float DeltaTime)
{
    Super::Tick(DeltaTime);

    if (WebSocket && WebSocket->IsConnected())
    {
        WebSocket->Send(TEXT("Hello from Unreal Engine!"));
    }
}
Enter fullscreen mode Exit fullscreen mode

3. Unity WebSocket Client (For Comparison)

Unity, in comparison to Unreal, tends to take a simpler approach, making it a great tool for those looking for a lightweight but effective solution. Here's how we would implement the same functionality in Unity:

Install the WebSocketSharp package via NuGet or import a WebSocket plugin.

Create a WebSocket Client script:

using System.Collections;
using UnityEngine;
using WebSocketSharp;

public class WebSocketClient : MonoBehaviour
{
    private WebSocket ws;

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

        ws.OnOpen += (sender, e) => {
            Debug.Log("WebSocket connected.");
        };

        ws.OnMessage += (sender, e) => {
            Debug.Log("Received: " + e.Data);
            // Handle the message
            HandleMessage(e.Data);
        };

        ws.Connect();
    }

    void HandleMessage(string message)
    {
        if (message.Contains("color"))
        {
            GetComponent<Renderer>().material.color = Color.red; // Example for Unity
        }
    }

    void Update()
    {
        if (ws != null && ws.IsAlive)
        {
            ws.Send("Hello from Unity!");
        }
    }

    void OnApplicationQuit()
    {
        if (ws != null)
        {
            ws.Close();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

4. Comparing Unreal Engine and Unity: Two Teachers with Different Styles

Unreal Engine, with its robust C++ system and highly detailed asset handling, is like a teacher who guides students through complex lessons with deep immersion. You might find yourself learning advanced concepts more quickly, but the complexity can be a challenge at times.

Unity, on the other hand, offers a more accessible approach. It’s like a teacher who simplifies concepts, helping students to get their hands dirty with real-world projects more quickly. If you’re looking to develop a simpler WebSocket-based application, Unity’s environment may be more suitable for rapid prototyping.

Despite these differences, both engines excel in real-time communication, making them great choices for interactive applications. The choice between Unity and Unreal Engine comes down to your project’s needs—whether you need the high fidelity of Unreal or the rapid iteration and flexibility of Unity.

5. Conclusion

By using WebSockets, both Unreal Engine 5 and Unity can effectively communicate with a Node.js WebSocket server, enabling real-time interactions in a variety of applications. Whether you're using Unreal Engine's immersive world-building tools or Unity’s fast-paced development cycle, WebSocket communication is a powerful tool for creating interactive, dynamic experiences.

Top comments (0)