避免为每个WS客户端创建onMessage函数

时间:2017-11-15 13:54:30

标签: javascript node.js websocket

按照coefs <- sapply(1:n, function(z){ train_indices <- dat_list[[z]] m <- lm(price ~ carat, data = dat[train_indices,]) return(unname(m$coefficients[2])) }) 的说明创建WebSocket服务器:

ws

为每个客户创建一个名为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('something'); }); 的onMessage回调,我是对的吗?

想象一下拥有两百万个客户。此代码将创建200万个函数。有办法避免这种情况吗?这样的事情会很精彩:

incoming

1 个答案:

答案 0 :(得分:-1)

怎么样:

const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8080 });

function handleMessage(message) {
  console.log('received: %s', message);	
}

wss.on('message', handleMessage);