我有与websocket
模块,可以通过以下命令安装了Node.js的服务器:
npm install websocket
从this guide开始,我决定把它扩大所有客户端之间共享发送的消息。
这是我(简化)服务器的代码:
#!/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,
autoAcceptConnections: false
});
var connectedClientsCount = 0; // ADDED
var connectedClients = []; // ADDED
wsServer.on('request', function(request) {
var connection = request.accept('echo-protocol', request.origin);
connectedClientsCount++;
connectedClients.push(connection);
console.log((new Date()) + ' Connection accepted.');
connection.on('message', function(message) {
if (message.type === 'utf8') {
console.log('Received Message: ' + message.utf8Data);
for(c in connectedClients) // ADDED
c.sendUTF(message.utf8Data); // ADDED
}
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) {
// here I should delete the client...
console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
});
});
在这种情况下,我可以得到connectedClientsCount
价值,但我不能管理connectedClients
列表。
我也试图与((eval)c).sendUTF(message.utf8Data);
作为语句,但它不工作。
我建议你使用Socket.IO:跨浏览器的WebSocket用于实时应用。该模块是非常简单的install and configure
例如:服务器
...
io.sockets.on('connection', function (socket) {
//Sends the message or event to every connected user in the current namespace, except to your self.
socket.broadcast.emit('Hi, a new user connected');
//Sends the message or event to every connected user in the current namespace
io.sockets.emit('Hi all');
//Sends the message to one user
socket.emit('news', {data:'data'});
});
});
...
客户:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
//receive message
socket.on('news', function (data) {
console.log(data);
//send message
socket.emit('my other event', { my: 'data' });
});
</script>
更多关于exposed events
尝试更换for ... in
通过for ... of
for(c of connectedClients) // ADDED
c.sendUTF(message.utf8Data); // ADDED