WebSocket Client - C++

Introduction WebSocket is a communication protocol used in networking allowing full-duplex communication. You can learn more about it here. This page shows how to use the WebSockets module built in...

Updated over 2 years ago Edit Page Revisions

Introduction

WebSocket is a communication protocol used in networking allowing full-duplex communication. You can learn more about it here. This page shows how to use the WebSockets module built in Unreal Engine 4 to create a client communicating with a WebSocket server in C++.

Setup

Adding the WebSocket module

To use this module, we need to update the project's .Build.cs.
Open MyProject/Source/MyProject/MyProject.build.cs and add "WebSockets" to the public dependency module names :

// Copyright 1998-2020 Epic Games, Inc. All Rights Reserved.
using UnrealBuildTool;
    
public class MyProject: ModuleRules
{
    public MyProject(ReadOnlyTargetRules Target) : base(Target)
    {
        // Other code...
    
        PublicDependencyModuleNames.AddRange(new string[] { "WebSockets" });
    }
}

For the includes files to work with your IDE, you might want to close your IDE and regenerate project files.

Utilisation

Header files

#include "WebSocketsModule.h" // Module definition
#include "IWebSocket.h"       // Socket definition

Creating the socket

The socket allows us to send or receive messages from the server. To create it, we call the CreateWebSocket function from the module.

const FString ServerURL = TEXT("ws://127.0.0.1:3000/"); // Your server URL. You can use ws, wss or wss+insecure.
const FString ServerProtocol = TEXT("ws");              // The WebServer protocol you want to use.
    
TSharedPtr<IWebSocket> Socket = FWebSocketsModule::Get().CreateWebSocket(ServerURL, ServerProtocol);

Connecting to the server

Before connecting to the server, we need to at least bind the events OnConnection and OnConnectionError.

We are using lambdas here for readability. You can bind UObject or any other function as they are basic delegates.

// We bind all available events
Socket->OnConnected().AddLambda([]() -> void {
    // This code will run once connected.
});
    
Socket->OnConnectionError().AddLambda([](const FString & Error) -> void {
    // This code will run if the connection failed. Check Error to see what happened.
});
    
Socket->OnClosed().AddLambda([](int32 StatusCode, const FString& Reason, bool bWasClean) -> void {
    // This code will run when the connection to the server has been terminated.
    // Because of an error or a call to Socket->Close().
});
    
Socket->OnMessage().AddLambda([](const FString & Message) -> void {
    // This code will run when we receive a string message from the server.
});
    
Socket->OnRawMessage().AddLambda([](const void* Data, SIZE_T Size, SIZE_T BytesRemaining) -> void {
    // This code will run when we receive a raw (binary) message from the server.
});
    
Socket->OnMessageSent().AddLambda([](const FString& MessageString) -> void {
    // This code is called after we sent a message to the server.
});
    
// And we finally connect to the server. 
Socket->Connect();

Sending data

To send data, we use the Send method on our connected socket. The Send method is overloaded and can send either raw binary or a string.

if (!Socket->IsConnected())
{
    // Don't send if we're not connected.
    return;
}
    
const FString StringMessage = TEXT("Hello there !");
const TArray BinaryMessage = { 'H', 'e', 'l', 'l', 'o', ' ', 't', 'h', 'e', 'r', 'e', ' ', '!' };
  
Socket->Send(StringMessage);
Socket->Send(BinaryMessage.GetData(), sizeof(uint8) * BinaryMessage.Num());

Closing the connection

If you want to close the connection from the client side, call

Socket->Close()

References

Engine WebSockets API page.