How to connect Unreal Engine 4 to local server via WebSocket using blueprints?

Suppose you faced the same problem as me: you need to create Connection Manager for Unreal Engine 4 project to get some values from server (which doesn’t exist yet, so we will use local solution) in real time. When I ran into a problem I googled a lot, but couldn’t find any tutorials or usable solutions. So I decided to write my own.

Here is my step-by-step guide to wonderful world of Unreal Engine 4, websockets and Node.js. I hope it will be useful for my fair readers.

Target audience — beginners, but skilled UE4 developers are also welcome!


Adding plugin to Unreal Engine 4 project

As I said earlier, we need to keep persistent connection with server to get values regularly, in real time. For that reason I decided to use WebSocket technology (read more about sockets). After small research I chose Socket.io plugin due to its simplicity, clarity and blueprints support.

Of course, if we want to use a plugin, at first we need to connect it with our project. But we can’t add plugins to “Blueprint Only” project, only to C++ project. To convert, we need to complete the following steps:

  1. At first, we need to create any C++ class: in Unreal Editor click “Add New” → “New C++ Class

2. In pop-up window choose “None” and click on “Create class”.

3. After C++ will be compiled, close Unreal Editor, go to your project’s folder, click on .uproject file and choose “Generate Visual Studio Project Files”.

Now we can add plugin to project!

Here are the steps to add Socket.io plugin to UE4 project:

  1. Download last release
  2. Unpack downloaded archive and find Plugins folder inside
  3. Copy-paste Plugins folder to your project root folder
  4. Open your project, go to Edit Plugins
  5. Find Project tab and enable SocketIOClient plugin.
  6. Restart Unreal Editor

Now you have SocketIOClient plugin in your project.


Creating Connection Manager

SocketIOClient plugin can be added to blueprint as component. So, let’s make simple Connection Manager.

Create Blueprint with Actor as parent class and put it on your level. It will be our manager. Open blueprint, click on “Add Component” and choose component named SocketIOClient.

Now we will add some logs to make communication with server more understandable: choose SocketIOClient and check its “Events” properties section. Here you can add bindings to socket events.

SocketIOClient component settings

Add “On Connected”, “On Disconnected” and “On” events. Let’s look at each one.

“On Connected” is called when project connects to server. By default, SocketIOClient connects to server, specified in component settings, automatically. I recommend you to add Print String method here with something like “Wow, connected!”

“On Disconnected” is called when connection breaks.

My useful logs

“On” is the most interesting event for us. It fires every time server send something to client (your project).

So, now we know when project establishes connection, disconnects and get messages from server. For further steps we need to unleash our imagination. Suppose we need server to send us new data every few seconds. Just random data, for example, direction of wind. In other words, server will call event named like “new wind” every 3 seconds to send data.

Ok, now we know event name. How will we receive it in Unreal Engine project?

At first, we need to call Bind Event function, where we will specify server-side event’s name as a param (“new wind”). It’s better to do it in Begin Play event.

Binding to “new wind” server event

Now we will receive messages from “new wind” server event in our “On” event. Let’s check that our incoming message is from “new wind” event using string comparison and, if check result is true, print message from server to screen (don’t forget to convet json value to string).

Getting values from server with “On” event

Ok, now everything is ready except one thing: our simple local server.


Creating local server

I decided to create local server using Node.js technology. I’ll skip base theory (you can read it here) and just post here my server’s code:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var util = require('util');
var clients = [];
io.on('connection', function(socket){
clients.push(socket.id);
var clientConnectedMsg = 'User connected ' + util.inspect(socket.id) + ', total: ' + clients.length;
console.log(clientConnectedMsg);
socket.on('disconnect', function(){
clients.pop(socket.id);
var clientDisconnectedMsg = 'User disconnected ' + util.inspect(socket.id) + ', total: ' + clients.length;
console.log(clientDisconnectedMsg);
})
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
function getRandomInRange(min, max) {
return Math.random() * (max - min) + min;
}
function sendWind() {
console.log('Wind sent to user');
io.emit('new wind', getRandomInRange(0, 360));
}
setInterval(sendWind, 3000);

How it works: it creates local server on port 3000. It means, you can access it via http://localhost:3000 address. Then server starts sending random values to client every 3 seconds.

To generate wind direction value we use getRandomInRange(min, max) function, that returns random number in specified range.

To send wind data to client, we need to call sendWind() function. To repeat it every 3 seconds, we use setInterval(<name function>, <interval in milliseconds>) event loop.


Testing all together

When we run the script, following message appears: “listening on *:3000”. It says us that everything went fine and server is working. Also “Wind sent to user” messages start printing every 3 seconds. I hope, you understand what it means (if no — look up at the first paragraph after the code snippet).

After we press “Play” button in Unreal Editor, you will see “User connected … “ message in terminal and in your UE4 project’s log (if you print it after OnConnected event fires). In few seconds we will start receiving random wind directions from local server.

Hooray, we did it!

Possible problems:

  • If you get “cannot find module” error while trying to run server script, check this Stack Overflow answer and install problem module in the same way.
  • If you didn’t see “User connected …” message in terminal, check game level: perhaps you forgot to add Connection Manager blueprint actor on it.
  • If you can’t get data from server with “On” event, check your Bind Event function and event name comparison after “On” event: event name in Bind Event = event name in comparison after “On” = first argument of io.emit(‘new wind’, getRandomInRange(-180, 180)) function on server.

Please, feel free to leave a comment if you found mistake or you have ideas about optimization.

Thank you!