Skip to content

Instantly share code, notes, and snippets.

@gamerxl
Last active January 6, 2024 04:17
Show Gist options
  • Save gamerxl/34a9f92418abf2b77fdc6b991bf470ea to your computer and use it in GitHub Desktop.
Save gamerxl/34a9f92418abf2b77fdc6b991bf470ea to your computer and use it in GitHub Desktop.
How to create a websocket client / connection without setup third party libraries in ue4 c++ context.
/**
* Include the PrivateDependencyModuleNames entry below in your project build target configuration:
* // Depend on WebSockets library from UE4 (UE4 WebSockets implementation is built upon the libwebsockets library).
* PrivateDependencyModuleNames.AddRange(new string[] { "WebSockets" });
*/
#include "WebSocketsModule.h"
#include "IWebSocket.h"
{
const FString ServerURL = TEXT("ws://localhost:3000/live");
const FString ServerProtocol = TEXT("ws"); // Supported protocols are: 'ws', 'wss', or 'wss+insecure'.
TSharedRef<IWebSocket> Socket = FWebSocketsModule::Get().CreateWebSocket(ServerURL, ServerProtocol);
Socket->OnConnected().AddLambda([Socket]() {
UE_LOG(LogTemp, Log, TEXT("Connected to websocket server."));
Socket->Send("{\"event\": \"test\", \"data\": \"test message data\"}");
});
Socket->OnConnectionError().AddLambda([](const FString& Error) {
UE_LOG(LogTemp, Log, TEXT("Failed to connect to websocket server with error: \"%s\"."), *Error);
});
Socket->OnMessage().AddLambda([](const FString& Message) {
UE_LOG(LogTemp, Log, TEXT("Received message from websocket server: \"%s\"."), *Message);
});
Socket->OnClosed().AddLambda([](int32 StatusCode, const FString& Reason, bool bWasClean) {
UE_LOG(LogTemp, Log, TEXT("Connection to websocket server has been closed with status code: \"%d\" and reason: \"%s\"."), StatusCode, *Reason);
});
Socket->Connect();
}
/**
* For instance a minimal WebSockets server based on nodejs and the ws package (https://www.npmjs.com/package/ws).
* Install the package mentioned above first:
* npm install --save ws
*/
const WebSocket = require('ws');
const webSocketServer = new WebSocket.Server({ port: 3000 });
webSocketServer.on('connection', (webSocketConnection) => {
console.log('Received connection from UE4 WebSocket client.');
webSocketConnection.on('message', (message) => {
console.log('Received message from UE4 WebSocket client: %s.', message);
});
webSocketConnection.send('{"event": "welcome", "data": "welcome message data"}');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment