admin管理员组

文章数量:1291116

I've been struggling with setting up a WebSocket server in Node.js for weeks. I've gone through the ws and Node.js documentation multiple times but still can't connect to my server.

WebSocket Server Code (server.js)

var app = require('../app');
var debug = require('debug')('ohoapp:server');
var http = require('http');
var { WebSocketServer } = require('ws');

/**
 * Get port from environment and store in Express.
 */
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

/**
 * Create HTTP server.
 */
var server = http.createServer(app);

var wss = new WebSocketServer({ 
    server: server,  
    clientTracking: true, 
    host: "openheroodyssey" 
});

wss.on('listening', () => {
    console.log('WebSocket Server listening on port ' + wss.address().port);
    console.log("WS address: " + wss.address().address);
    console.log("WS family: " + wss.address().family);
});

wss.on('connection', (socket, req) => {
    console.log("Connection established");
    socket.send("Connection established!");

    socket.on('message', (message, isBinary) => {
        wss.clients.forEach((client) => {
            if (client.readyState === WebSocket.OPEN && ws !== client) {
                client.send(message, { binary: isBinary });
            }
        });
        console.log(message);
    });

    socket.on('close', () => {
        console.log('Connection closed');
    });
});

server.on('error', onError);
server.on('listening', onListening);

server.listen(port, () => {
    console.log("HTTP/S server listening on port: " + port);
});

function normalizePort(val) {
    var port = parseInt(val, 10);
    if (isNaN(port)) return val;
    if (port >= 0) return port;
    return false;
}

What Works ✅

  • The server starts successfully.
  • Console logs show the WebSocket server is listening.
  • The port number is correctly logged.

What Doesn’t Work ❌

  • The WebSocket address (wss.address().address) is not displaying correctly in the console.
  • Clients (Postman, WebSocketKing) cannot connect to the server.
  • I tried connecting using multiple WebSocket URLs:
    • wss://www.openheroodyssey:8081
    • ws://www.openheroodyssey:8081
    • Without www
    • Without specifying the port

Console Output

When I start the server, this is what I see in the logs:

2025-02-13 19:52:31 default[20250213t194835] WebSocket Server listening on port 8081  
2025-02-13 19:52:31 default[20250213t194835] WS address: ::  
2025-02-13 19:52:31 default[20250213t194835] WS family: IPv6  

I originally had .toString() at the end of console.log(wss.address().address), but removing it didn’t change the output.

What I’ve Tried

本文标签: