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 or reseller hosting accounts.


Supported Hosting Plans

  • Managed or unmanaged VPS

  • Dedicated servers


Step 1: Web Server Configuration

Without Root Access

Open a support ticket at Hosting.com with:

  • Domain/URL for WebSocket proxy

  • Port number of your WebSocket server

With Root Access

You can configure your web server directly:


Step 2: WebSocket Server Application

Python Server Example

  1. Ensure Python ≥3.9 is installed.

  2. Create a virtual environment and install the websockets library:

ssh user@server
python3 -m venv websocketenv
cd websocketenv
source bin/activate
pip install websockets
  1. Create server.py with the following content:

#!/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())
  1. Start the server:

python3 server.py

Node.js Server Example

  1. Ensure Node.js ≥16 is installed.

  2. Install the ws library:

ssh user@server
npm install ws
Create 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());
  });
});

  1. Start the server:

node server.mjs

Important: Save with .mjs extension.


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.com with your server’s domain or IP.

  • Load this page in a browser to test the WebSocket connection.


Step 4 (Optional): Make the Server Persistent

Create a systemd service to auto-start your WebSocket server.

Python Service Example

/etc/systemd/system/websocket-server.service:

[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

Node.js Service Example

[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

Commands to Enable the Service

chmod 664 /etc/systemd/system/websocket-server.service
systemctl --system daemon-reload
systemctl start websocket-server.service
systemctl status websocket-server.service
systemctl enable websocket-server.service

Your 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.

這篇文章有幫助嗎? 0 用戶發現這個有用 (0 投票)

Powered by WHMCompleteSolution