我不知道这是你正在使用的包装,但是你使用的包装都是类似的。 在自述文件中,它有两个例子:
服务器示例
在服务器示例中,他们创建一个Web套接字服务器:const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
ws.send('hello from the server!');
});
这样做是为了创建侦听套接字服务器。 它为message添加了一个事件监听器,因此当客户端连接到服务器时,客户端就可以发送消息,并且事件处理程序将触发。
在该事件监听器之后,它'hello from the server!'发送字符串'hello from the server!' 。 该发送调用不会触发上述事件处理程序,因为此发送调用发生在套接字的服务器端。 它正在该套接字的客户端发送要接收的消息。
客户端示例(通常在浏览器中)const WebSocket = require('ws'); // omit this line if including ws via tag
const ws = new WebSocket('ws://www.host.com/path');