This article describes how to configure and use WebSocket connections on a VPS or Dedicated server.
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.
A2 Hosting supports WebSocket connections on the following plans:
The following procedures guide you through the process of setting up and using WebSocket connections.
The first step is to enable WebSocket connections on the web server. How you do this depends on your account type:
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:
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.
To run WebSockets in Python, use the websockets library.
To set up a Python virtual environment, install the websockets library, and create a server application, follow these steps:
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.
To run WebSockets in Node.js, use the ws library.
To install the ws library and create a server application, follow these steps:
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()); }); });
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.
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.
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.
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:
[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
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
Subscribe to receive weekly cutting edge tips, strategies, and news you need to grow your web business.
No charge. Unsubscribe anytime.
Did you find this article helpful? Then you'll love our support. Experience the A2 Hosting difference today and get a pre-secured, pre-optimized website. Check out our web hosting plans today.
We use cookies to personalize the website for you and to analyze the use of our website. You consent to this by clicking on "I consent" or by continuing your use of this website. Further information about cookies can be found in our Privacy Policy.