Configuring and using WebSocket connections
Ce contenu n’est pas encore disponible dans votre langue.
Configuring and Using WebSocket Connections on VPS or Dedicated Servers
Section titled “Configuring and Using WebSocket Connections on VPS or Dedicated Servers”WebSockets allow persistent, two-way communication between a browser and server over a single TCP socket, enabling real-time, responsive web applications.
Note: WebSockets are not supported on shared hosting accounts.
Supported Hosting Plans
Section titled “Supported Hosting Plans”- Managed or unmanaged VPS
- Dedicated servers
Step 1: Web Server Configuration
Section titled “Step 1: Web Server Configuration”Without Root Access
Section titled “Without Root Access”Open a support ticket in the Ruachost client area with:
- Domain/URL for WebSocket proxy
- Port number of your WebSocket server
With Root Access
Section titled “With Root Access”You can configure your web server directly:
- Apache: mod_proxy_wstunnel documentation
- Nginx: WebSocket documentation
- Other web servers: refer to their respective documentation
Step 2: WebSocket Server Application
Section titled “Step 2: WebSocket Server Application”Python Server Example
Section titled “Python Server Example”- Ensure Python ≥3.9 is installed.
- Create a virtual environment and install the
websocketslibrary:
ssh user@serverpython3 -m venv websocketenvcd websocketenvsource bin/activatepip install websockets- Create
server.pywith the following content:
#!/usr/bin/env pythonimport asynciofrom 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())- Start the server:
python3 server.pyNode.js Server Example
Section titled “Node.js Server Example”- Ensure Node.js ≥16 is installed.
- Install the
wslibrary:
ssh user@servernpm install wsCreate 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()); });});- Start the server:
node server.mjsImportant: Save with
.mjsextension.
Step 3: WebSocket Client
Section titled “Step 3: WebSocket Client”Create a test HTML page:
<!DOCTYPE html><html><head> <title>WebSocket test</title><script>"use strict";
function webSocketTest() { let socket = new WebSocket("wss://example.com/");
socket.onopen = function(event) { alert("Connection established"); 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(event) { alert(`[error]`); };}</script></head><body onload="webSocketTest()"> <p>WebSocket test</p></body></html>- Replace
example.comwith your server’s domain or IP. - Load this page in a browser to test the WebSocket connection.
Step 4 (Optional): Make the Server Persistent
Section titled “Step 4 (Optional): Make the Server Persistent”Create a systemd service to auto-start your WebSocket server.
Python Service Example
Section titled “Python Service Example”/etc/systemd/system/websocket-server.service:
[Unit]Description=WebSocket Server DaemonAfter=network-online.target
[Service]ExecStart=/home/username/sockenv/bin/python3 /home/username/sockenv/server.pyRestart=alwaysRestartSec=5
[Install]WantedBy=multi-user.targetNode.js Service Example
Section titled “Node.js Service Example”[Unit]Description=WebSocket Server DaemonAfter=network-online.target
[Service]ExecStart=/home/username/bin/node /home/username/server.mjsRestart=alwaysRestartSec=5
[Install]WantedBy=multi-user.targetCommands to Enable the Service
Section titled “Commands to Enable the Service”chmod 664 /etc/systemd/system/websocket-server.servicesystemctl --system daemon-reloadsystemctl start websocket-server.servicesystemctl status websocket-server.servicesystemctl enable websocket-server.serviceYour WebSocket server will now start automatically on boot and restart if it crashes.
This setup provides a full WebSocket stack: server, client, and persistent system service.
Cette page vous a-t-elle aidé ?
Merci pour votre retour.