我发现很难发出一个事件,因为我不太了解创建一个事件/发出一个带有套接字IO的事件.
这是CASE"/ publish"的问题:
var app = http.createServer(function (req, res) { if (req.method == "OPTIONS") { res.header('Access-Control-Allow-Origin', '*:*'); res.send(200); } else { var u = url.parse(req.url,true), body = ''; req.on('data',function(chunk) { body += chunk; }); req.on('end',function() { if(body) { var data =JSON.parse(body); if(data._app_secret && data._app_secret == 'nonexistent') { switch(u.pathname) { case '/generateusersecret' : findTokenByUser(req.headers.host+'_'+data.user_id,function(reply) { if(reply) { jsonResponse(res,{userSecret : reply}); } else { generateToken(req.headers.host + '_' + data.user_id,data.user_id,res); } }); break; case '/getusersecret' : findTokenByUser(req.headers.host + '_' + data.user_id,function(reply) { jsonResponse(res,{userSecret : reply}); console.log(reply); }); break; case '/publish': if(data.type == 'notification'){ var newData = { item_id : data.item_id, message : data.message, recipient : data.channel, itemLink : data.itemLink, timestamp : data.timestamp, read : 0 } notification = JSON.stringify(newData); // I need to emit my event here Socket.emit(THE EVENT HERE,notification DATA) } break; default: jsonResponse(res,{error : "Unknown Command: " + u.pathname}); break } } else { res.writeHead(403, {'Content-Type': 'text/plain'}); res.end('Not authorized'); } } }); } }); app.listen(config.port || 4000, null);
然后我需要听听:
io.sockets.on('connection'function(socket){ socket.on('THE EVENT HERE',function(NOTIFICATION DATA){ //I NEED TO EMIT ANOTHER EVENT HERE }) })
有可能这样吗?我必须这样做,因为我使用PHP的cURL,我无法在客户端发出,所以我需要在服务器端发出它.
看来你需要从服务器端发出一个事件,这是可能的,也是socket.io的主要功能.
要广播到所有连接的套接字,请在/publish
端点中使用此代码:
io.sockets.emit('event', data);
Socket.io还可以向一组套接字广播消息,此功能称为房间.
如果要仅向一个套接字发送消息,则可以在连接时标记具有额外属性的套接字,然后在连接套接字列表中搜索这些套接字.
完整的例子:
var http = require('http'); var fs = require('fs'); var server = http.createServer(handler); var io = require('socket.io').listen(server); function handler (req, res) { if (req.url === '/') { return fs.createReadStream(__dirname + '/index.html').pipe(res); } if (req.url === '/publish' && req.method === 'POST') { //this is what you are looking for: io.sockets.emit('super event', { message: 'hello' }); //--------------------------------- res.writeHead(200, { 'Location': '/' }); return res.end(''); } } io.sockets.on('connection', function (socket) { socket.on('publish', function (data) { //if you need to emit to everyone BUT the socket who emit this use: //socket.broadcast.emit('super event', data); //emit to everyone io.sockets.emit('super event', data); }) }); server.listen(1080, function () { console.log('listening on http://localhost:1080'); });
<html> <head> </head> <body> hello world. <form action="/publish" method="post"> <input type="submit" value="send a notification"></input> </form> <script src="/socket.io/socket.io.js"></script> <script> var socket = io.connect('/'); socket.on('super event', function (data) { console.log(data); alert('got a message!'); }); </script> </body> </html>
将这两个文件放在一个目录中.
npm i socket.io
node server.js
在浏览器中打开指向的两个选项卡 http://localhost:1080
单击其中一个选项卡中的"发送通知"按钮