我有一个Node服务器,其中包含以下代码:
var server = require('http').createServer(handler);
var io = require('socket.io')(server);
var fs = require('fs');
function handler(request,response) {
if (request.url == '/123') {
// The following line says that socket is undefined.
//socket.emit('case_updated', 123);
}
response.writeHead(200, {'Location' : '/'});
return response.end('');
}
io.sockets.on('connection', function (socket) {
socket.on('case_updated', function(caseNumber){
socket.broadcast.emit('case_updated', caseNumber);
});
});
server.listen(3000);
现在,我希望在访问该URL时触发socket.broadcast.emit
。
答案 0 :(得分:0)
找到问题的解决方案。
我刚刚在服务器所在的同一个地方安装了socket.io-client
软件包,并在服务器代码中实例化了客户端,并且我能够使用socket.emit
函数。在if语句中的handler函数中,我正在创建一个客户端。
var server = require('http').createServer(handler);
var io = require('socket.io')(server);
var fs = require('fs');
function handler(request,response) {
if (request.url == '/123') {
//192.168.2.100 is the ip of the same server where this code is located.
var socket_client = require("socket.io-client")('http://192.168.2.100:3000');
socket_client.on('connect', function () {
socket_client.emit('case_updated', 123);
});
}
response.writeHead(200, {'Location' : '/'});
return response.end('');
}
io.sockets.on('connection', function (socket) {
socket.on('case_updated', function(caseNumber){
socket.broadcast.emit('case_updated', caseNumber);
});
});
server.listen(3000);