node.js + WebSocketを使用しています。
クライアント側からメッセージを送るとサーバ側で受信できることは確認したのですが、
サーバから接続されている全クライアントに送信するにはどのように変更すればよいのでしょうか?
色々調べた中で見たサンプルはサーバ側でhoge.clients.forEachみたいな感じでループでsendを実行していますが、上手く行きません(clientsがどこにあるのか?)どのようにして、接続されている全てのクライアント情報を取得できるのでしょうか?
また気になっているのは、多くのサンプルではサーバ側で"connection"onで監視していますが、自分のサーバ側ではconnectionは監視できなく、requestになっています(拾ったサンプルのまま)
よろしくご教示ください。
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ var WebSocketServer = require('/home/hoge/app/nodejs/node_modules/websocket').server; var http = require('http'); var server = http.createServer(function(request, response) { console.log((new Date()) + ' Received request for ' + request.url); var content = "test"; response.writeHead(200, {'Content-Type': 'text/html', 'Content-Length': content.length} ); response.end(); }); server.listen(9001, function() { console.log((new Date()) + ' Server is listening on port 9001'); }); 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.'); }); });
this.websocket = new WebSocket(hogehogeURL, ['echo-protocol','soap', 'xmpp']);
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。