Configuring and using WebSocket connections
This article demonstrates how to configure and use WebSocket connections on a VPS or Dedicated server. Please note that WebSocket connections are not supported on shared or reseller hosting accounts at this time.
This article describes how to configure and use WebSocket connections on a VPS or Dedicated server.
About WebSocket connections
The WebSocket protocol enables you to establish persistent, two-way communication between a browser and a server over a single TCP socket. Web applications can then be responsive in real-time, without the need to poll a server for new information.
Hosting.com supports WebSocket connections on the following plans:
-
VPS (managed and unmanaged).
-
Dedicated servers.
Note
Hosting.com does not support WebSockets on shared or reseller hosting accounts at this time.
The following procedures guide you through the process of setting up and using WebSocket connections.
Step 1: Web server configuration
The first step is to enable WebSocket connections on the web server. How you do this depends on your account type:
-
If you do not have root access to your server, our support team will configure the web server for you. Please open a support ticket at https://my.hosting.com and provide the following information:
-
The domain or URL you want to proxy for WebSocket connections.
-
The port number on which your WebSocket server application runs.
-
-
If you do have root access to your server, you can configure your web server for WebSocket connections on your own. The exact steps to do this depend on the web server you are running:
-
For information about how to configure Apache for WebSockets, please see https://httpd.apache.org/docs/2.4/mod/mod_proxy_wstunnel.html.
-
For information about how to configure Nginx for WebSockets, please see https://nginx.org/en/docs/http/websocket.html.
-
For information about how to configure other web servers for WebSockets, please see the relevant documentation.
-
Step 2: WebSocket server application
After you configure the web server to route WebSocket connections, you are ready to run a WebSocket server application that accepts and processes those connections. You can write this application using any programming language, but the most common implementations are in Python or Node.js. Functionally-equivalent code samples for these two languages are below.
Important
These code samples are for proof-of-concept purposes, and are not intended for production use. You should make sure your own code is suitable for a production environment.
Code sample - Python
To run WebSockets in Python, use the websockets library.
Note
You should run a newer Python version on the server (at least Python 3.9). If the server’s package repositories only have older Python versions, you can download and compile Python yourself. For information about how to do this, please see this article.
To set up a Python virtual environment, install the websockets library, and create a server application, follow these steps:
-
Log in to the server using SSH.
-
At the command prompt, type the following commands:
python3 -m venv websocketenv cd websocketenv source bin/activate pip install websockets
-
To create a basic WebSockets server that runs on port 5678, copy the following code and paste it into a file named server.py:
#!/usr/bin/env python import asyncio from websockets.asyncio.server import serve async def echo(websocket): async for message in websocket: print('Received [' + message + ']') await websocket.send(message) async def main(): async with serve(echo, "localhost", 5678) as server: await server.serve_forever() if __name__ == "__main__": asyncio.run(main())
-
Within the virtual environment, type the following command to start the server:
python3 server.py
The WebSocket server application is now running, and you are ready to set up the WebSocket client.
Code sample - Node.js
To run WebSockets in Node.js, use the ws library.
Note
You should run a newer Node.js version on the server (at least Node.js v16). If the server’s package repositories only have older Node.js versions, you can download and install a newer Node.js version yourself. For information about how to do this, please see this article.
To install the ws library and create a server application, follow these steps:
-
Log in to the server using SSH.
-
At the command prompt, type the following command:
npm install ws
-
To create a basic WebSockets server that runs on port 5678, copy the following code and paste it into a file named server.mjs:
import { WebSocketServer } from 'ws'; const wss = new WebSocketServer({ port: 5678 }); wss.on('connection', function connection(ws) { ws.on('error', console.error); ws.on('message', function message(data) { console.log('Received [%s]', data); ws.send(data.toString()); }); });
Important
Make sure you save the file with an .mjs extension, not .js.
-
Type the following command to start the server:
node server.mjs
The WebSocket server application is now running, and you are ready to set up the WebSocket client.
Step 3: WebSocket client
At this point, the web server is configured to tunnel WebSocket connections, and you have a running WebSocket server. You are now ready to set up and test WebSocket connections from a web browser.
Code sample - Client web page
This basic web page contains a JavaScript function that opens a secure WebSocket connection and sends some data to the server, which the server then echoes back to the client. In line 9, make sure you replace example.com with your own server’s domain name (or IP address):
<!DOCTYPE html>
<html>
<head>
<title>WebSocket test</title>
<script>
"use strict";
function webSocketTest() {
let socket = new WebSocket("wss://example.com/");
socket.onopen = function(e) {
alert("Connection established");
alert("Sending data to server");
socket.send("Hello from WebSockets");
};
socket.onmessage = function(event) {
alert(`Received data from server: ${event.data}`);
};
socket.onclose = function(event) {
if (event.wasClean) {
alert(`Connection closed cleanly, code=${event.code} reason=${event.reason}`);
} else {
alert('Connection died');
}
};
socket.onerror = function(error) {
alert(`[error]`);
};
}
</script>
</head>
<body onload="webSocketTest()">
<p>WebSocket test</p>
</body>
</html>
Save this page on the server, and then load it in your web browser. You should receive popup messages about the connection, and the client message "Hello from WebSockets" echoed back from the server.
Step 4 (optional): Making the server application persistent
In most cases, you will want your WebSocket server application to start automatically after the server reboots or if the application crashes. There are several ways to do this, but if you have root access to the server, a systemd service is quick and easy to set up. To do this, follow these steps:
-
Using your preferred text editor, in the /etc/systemd/system directory, create a file named websocket-server.service.
-
Copy one of the following text blocks, and then paste it into the websocket-server.service file. The first text block demonstrates how to start the Python-based WebSocket server application. The second text block demonstrates how to start the Node.js-based WebSocket server application. Update the paths and filenames in the ExecStart line as needed:
Starting a Python-based application
[Unit] Description=WebSocket Server Daemon After=network-online.target [Service] ExecStart=/home/username/sockenv/bin/python3 /home/username/sockenv/server.py Restart=always RestartSec=5 [Install] WantedBy=multi-user.target
Starting a Node.js-based application
[Unit] Description=WebSocket Server Daemon After=network-online.target [Service] ExecStart=/home/username/bin/node /home/username/server.mjs Restart=always RestartSec=5 [Install] WantedBy=multi-user.target
-
Save your changes to the websocket-server.service file.
-
At the command prompt, type the following commands:
chmod 664 /etc/systemd/system/websocket-server.service systemctl --system daemon-reload systemctl start websocket-server.service
-
To confirm the service started correctly, type the following command:
systemctl status websocket-server.service
-
To enable the service to start automatically when the server is rebooted, type the following command:
systemctl enable websocket-server.service
Related Articles
Updated 3 days ago