WebSocket Client - C++

From UE4: Community Wiki
Jump to: navigation, search


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++.


Adding the WebSocket module[edit]

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.

Loading the module[edit]

In order to use this module, we need to load it. To do so, we will load it on game instance initialization :

// MyProjectGameInstance.h
class MYPROJECT_API UMyProjectGameInstance : public UGameInstance
    virtual void Init() override;
// MyProjectGameInstance.cpp
#include "WebSocketsModule.h"
void UMyProjectGameInstance::Init()
    // Load the WebSockets module. An assertion will fail if it isn't found.
    FWebSocketsModule& Module = FModuleManager::LoadModuleChecked<FWebSocketsModule>(TEXT("WebSockets"));


Header files[edit]

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

Creating the socket[edit]

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://"); // 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[edit]

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

NOTE: 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. 

Sending data[edit]

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.
const FString StringMessage = TEXT("Hello there !");
const TArray<uint8> BinaryMessage = { 'H', 'e', 'l', 'l', 'o', ' ', 't', 'h', 'e', 'r', 'e', ' ', '!' };
Socket->Send(BinaryMessage.GetData(), sizeof(uint8) * BinaryMessage.Num());

Closing the connection[edit]

If you want to close the connection from the client side, call Socket->Close().


Engine WebSockets API page.