有没有可能拥有一个Node.js WebSocket客户端?

16

到目前为止,我只看到过在Node.js中将应用程序设置为WebSockets服务器的示例。通常客户端是基于浏览器的,我还没有看到Node.js客户端的示例。

为什么Node.js WebSockets客户端的示例这么少呢?另外,客户端与服务器之间的通信还有哪些其他选项?


@JeremyThille — Node.js通常运行在服务器上。然而,它是一个通用的运行时。 - Quentin
2个回答

28

实际上有许多不同的例子。

例如,我使用了websockets包。

https://www.npmjs.com/package/websocket

此代码演示了一个在Node.js中的客户端,而不是在浏览器中。

#!/usr/bin/env node
var WebSocketClient = require('websocket').client;

var client = new WebSocketClient();

client.on('connectFailed', function(error) {
    console.log('Connect Error: ' + error.toString());
});

client.on('connect', function(connection) {
    console.log('WebSocket Client Connected');
    connection.on('error', function(error) {
        console.log("Connection Error: " + error.toString());
    });
    connection.on('close', function() {
        console.log('echo-protocol Connection Closed');
    });
    connection.on('message', function(message) {
        if (message.type === 'utf8') {
            console.log("Received: '" + message.utf8Data + "'");
        }
    });

    function sendNumber() {
        if (connection.connected) {
            var number = Math.round(Math.random() * 0xFFFFFF);
            connection.sendUTF(number.toString());
            setTimeout(sendNumber, 1000);
        }
    }
    sendNumber();
});

client.connect('ws://localhost:8080/', 'echo-protocol');

如果您需要进一步的帮助,那就很简单,请告诉我们!


1
感谢您提供详细的答案! - mhovd
当然没问题 - Antax
1
谢谢提供示例。是否有保持连接并处理接收到的数据的示例? - Penalse
请尝试阅读此网站:https://www.npmjs.com/package/websocket[当前功能=>可调节设置状态: ->是否为了保持连接而自动发送ping帧 ->保持连接的ping间隔]请尝试阅读文档。例如,我手动完成了操作,但这也有另一个原因。数据需要在connection.on('message'...部分处理,因为这是接收数据的地方。 - Antax

5

你可以使用W3C Websocket API来开发在Node和浏览器上运行的应用程序(通过W3CWebSocket类)。

https://websockets.spec.whatwg.org

npm install websocket

服务器示例

这是一个简短的示例,展示了一个服务器,它可以回显任何发送给它的内容,无论是 UTF-8 还是二进制。

#!/usr/bin/env node
var WebSocketServer = require('websocket').server;
var http = require('http');

var server = http.createServer(function(request, response) {
    console.log((new Date()) + ' Received request for ' + request.url);
    response.writeHead(404);
    response.end();
});
server.listen(8080, function() {
    console.log((new Date()) + ' Server is listening on port 8080');
});

wsServer = new WebSocketServer({
    httpServer: server,
    // You should not use autoAcceptConnections for production
    // applications, as it defeats all standard cross-origin protection
    // facilities built into the protocol and the browser.  You should
    // *always* verify the connection's origin and decide whether or not
    // to accept it.
    autoAcceptConnections: false
});

function originIsAllowed(origin) {
  // put logic here to detect whether the specified origin is allowed.
  return true;
}

wsServer.on('request', function(request) {
    if (!originIsAllowed(request.origin)) {
      // Make sure we only accept requests from an allowed origin
      request.reject();
      console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
      return;
    }
    
    var connection = request.accept('echo-protocol', request.origin);
    console.log((new Date()) + ' Connection accepted.');
    connection.on('message', function(message) {
        if (message.type === 'utf8') {
            console.log('Received Message: ' + message.utf8Data);
            connection.sendUTF(message.utf8Data);
        }
        else if (message.type === 'binary') {
            console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
            connection.sendBytes(message.binaryData);
        }
    });
    connection.on('close', function(reasonCode, description) {
        console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
    });
});

客户端示例

这是一个简单的客户端示例,它会在控制台打印出接收到的任何utf-8消息,并定期发送一个随机数。

此代码演示了Node.js中的客户端,而不是浏览器中的客户端。

var W3CWebSocket = require('websocket').w3cwebsocket;

var client = new W3CWebSocket('ws://localhost:8080/', 'echo-protocol');

client.onerror = function() {
    console.log('Connection Error');
};

client.onopen = function() {
    console.log('WebSocket Client Connected');

    function sendNumber() {
        if (client.readyState === client.OPEN) {
            var number = Math.round(Math.random() * 0xFFFFFF);
            client.send(number.toString());
            setTimeout(sendNumber, 1000);
        }
    }
    sendNumber();
};

client.onclose = function() {
    console.log('echo-protocol Client Closed');
};

client.onmessage = function(e) {
    if (typeof e.data === 'string') {
        console.log("Received: '" + e.data + "'");
    }
};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接