javascript - How to emit event with Socket.io and Node.js? -


i find hard emit event because don't know creating event/emitting event socket io.

here problem on 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);                                      // need emit 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); 

then need listen on:

io.sockets.on('connection'function(socket){    socket.on('the event here',function(notification data){       //i need emit event here    }) }) 

is there possible way this? have because using php's curl , can't emit on client side need emit on server side.

it seems need emit event server-side, possible , main feature socket.io.

to broadcast connected sockets use code in /publish endpoint:

io.sockets.emit('event', data);

socket.io can broadcast messages group of sockets, feature called rooms.

if want send message 1 socket, can mark sockets property when connect , search sockets in list of connected sockets.


complete example:

server side (server.js):

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 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 need emit socket emit use:     //socket.broadcast.emit('super event', data);      //emit     io.sockets.emit('super event', data);   }) });  server.listen(1080, function () {   console.log('listening on http://localhost:1080'); }); 

client side (index.html):

<html> <head> </head> <body>     hello world.     <form action="/publish" method="post">         <input type="submit" value="send 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 message!');       });     </script> </body> </html> 

usage

  • put these 2 files in 1 directories.
  • npm socket.io
  • node server.js
  • open 2 tabs in browser pointing http://localhost:1080
  • click send notification button in 1 of tabs

Comments

Popular posts from this blog

python - Subclassed QStyledItemDelegate ignores Stylesheet -

java - HttpClient 3.1 Connection pooling vs HttpClient 4.3.2 -

SQL: Divide the sum of values in one table with the count of rows in another -