简体   繁体   中英

Sending asynchronous information with node.js and socket.io

I have the following problem: I'm trying to send data collected by AMI (asterisk.io) using the sockets.io module, but I'm having difficulty to printing it in the html file. In the code below, the idea was to show it on the console as the data came in. I really do not know how to make this work, can anyone help me? Thank you!

html file:

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io();
  socket.on('data', function(data){
    console.log(data);
  });
</script>

asterisk.io with socket.io file:

var socket = require('../app');
require('events').EventEmitter.prototype._maxListeners = 1000;
var aio = require('asterisk.io');

var io = socket.io;
var ami = null;
ami = aio.ami(
    '192.168.0.7',
    5038,
    'admin',
    'admin'
);
ami.on('error', function(err){
    throw err;
});
io.on('connection', function(socket){
  ami.on('ready', function(){
    ami.action('SIPpeers', {}, function(data){
      ami.on('eventPeerEntry', function(data){
        socket.on('data', function(data){
          io.emit('data', data);
        });
      });
    });
  });
});

my app.js file:

var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var http = require('http').Server(app);
var cookieParser = require('cookie-parser');
var session = require('express-session');
var io = require('socket.io')(http);
exports.io = io;

(...)

//Execute main
http.listen(7777, function(){
  console.log("Running...");
});

[EDIT] After the help of Vaterrenanburg, this is the right code:

asterisk.io

io.on('connection', function (socket) {
  ami.action('SIPpeers', {}, function(data){
    ami.on('eventPeerEntry', function(data){
      socket.emit("peer", data);
    });
  });
});

html file:

<script src="/socket.io/socket.io.js"></script>
<script>
    var socket = io.connect('http://localhost');
    socket.on('peer', function (data) {
        (...)
        console.log(data);
    });
</script>

Currently, you have it set up so that the server emits the data event only when the client emits the data event. I believe from your description that you want the server to emit the data event to the client on the ami eventPeerEntry event. To do this, remove the subscription to the data event on the server.

io.on('connection', function(socket){
  ami.on('ready', function(){
    ami.action('SIPpeers', {}, function(data){
      ami.on('eventPeerEntry', function(data){
        io.emit('data', data);
      });
    });
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM