Pusher: Cannot broadcast client event - javascript

I'm developing a conference app with laravel 5 and I decide to implement a webRTC solution for that. So, I use Pusher for signaling stuff, but I have a prob: I'm using SimplePeerJs for the webRTC things, when I trigger an event (after subscribing and others stuff), I have the following err:
Pusher : Error : {"type":"WebSocketError","error":{"type":"PusherError","data":{"code":null,"message":"Cannot broadcast client event (connection not subscribed to channel presence-chat)"}}}.
my code is:
Pusher.log = function(message) {
if (window.console && window.console.log)
{
window.console.log(message);
}
};
var currentUser = {
nom: '{{ auth()->user()->first_name }}',
id: {{ auth()->user()->id }},
stream: undefined
};
var pusher = new Pusher('my_app_key', {
authEndpoint: 'pusher/auth',
auth: {
headers: {
'X-CSRF-Token': '{{ csrf_token() }}'
},
params: {
name: currentUser.name,
id: currentUser.id
}
}
});
var channel = pusher.subscribe('presence-chat');
var callback = function() {
console.log('Channel members:', channel.members);
};
//
channel.bind('pusher:subscription_succeeded', callback);
channel.bind('pusher:subscription_error', function(PusherError){
console.log(PusherError);
});
channel.bind('pusher:member_added', function(){
console.log('Member Added');
});
channel.bind('pusher:member_removed', function(){
console.log('Member Removed');
});
//peers stuff
var peer = new SimplePeer({ initiator: true });
peer.on('signal', function (data) {
channel.trigger('client-signal-' + currentUser.id,
{
userId: currentUser.id,
data: data
});
});
peer.on('ready', function () {
peer.send('hey peer, how is it going?')
});
any ideas?
thanks.

The issue is that the Pusher client hasn't had a chance to connect and subscribe to the channel before the peer.on('signal') is being triggered. Did you try moving the peers stuff into the subscription callback ?
var callback = function() {
console.log('Channel members:', channel.members);
//peers stuff
var peer = new SimplePeer({ initiator: true });
peer.on('signal', function (data) {
channel.trigger('client-signal-' + currentUser.id,
{
userId: currentUser.id,
data: data
});
});
peer.on('ready', function () {
peer.send('hey peer, how is it going?')
});
});

Related

PeerJS not sending/receiving data

I am currently trying to make a 2 player HTML/JS boardgame and am using PeerJS to connect two players sessions together but cant get it to work.
Here is a quick test i havent been able to get to send/receive data even though connecting works
On the sending end
var peer = new Peer();
var con;
function c() {
con = peer.connect('id');
con.on('error', function(err) { alert(err); });
con.on('data', function(data){ console.log(data) });
};
function send() {
con.on('open', function(){
con.send('HELLO WORLD')
});
}
and on the receiving end:
var peer = new Peer('id');
peer.on('connection', function(con){
console.log('connected')
con.on('error', function(err) { alert(err) });
con.on('open', () => {
con.on('data', (data) => {
console.log('Incoming data', data);
con.send('REPLY');
});
});
});
You need to configure stun and turn servers for Peer. Here is complete working example.
/**********
var peer = new Peer({
config: {
'iceServers': [
{ url: 'stun:stun.l.google.com:19302' },
]
} /* Sample servers, please use appropriate ones */
*******/
<script src="https://unpkg.com/peerjs#1.3.1/dist/peerjs.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script type="text/javascript">
var peer = new Peer({
config: {
'iceServers': [
{ url: 'stun:stun.l.google.com:19302' },
]
} /* Sample servers, please use appropriate ones */
});
peer.on("open", function (id) {
$("#chat").hide()
$("#peerid").text(id)
$("form#connect").submit(function () {
var remoteID = $(this).find('input[type="text"]').val()
console.log("connect to", remoteID);
var conn = peer.connect(remoteID)
gotConnection(conn)
return false;
})
})
peer.on("connection", gotConnection)
function gotConnection(conn) {
conn.on("error", function (err) {
console.error("connection error", err, conn)
})
conn.on("open", function () {
console.log("conn open", conn)
$("#remoteid").text(conn.peer)
$("form#connect").hide()
$("#chat").show()
$("#chat form").submit(function () {
var message = $(this).find('input[type="text"]').val()
console.log("send", message);
conn.send(message)
$(this).find('input[type="text"]').val("")
$("#messages").append($('<li>' + peer.id + ': ' + message + '</li>'))
return false;
})
conn.on("data", function (data) {
console.log("got", data);
$("#messages").append($('<li>' + conn.peer + ': ' + data + '</li>'))
})
})
}
</script>

Error promise after publish data to MQTT broker in My Alexa Lambda node js

I have problem with my Lambda, actually in promise nodejs. I have wrote code like this in my Lambda:
'use strict'
const Alexa = require('alexa-sdk');
const mqtt = require('mqtt');
const APP_ID = undefined;
const WELCOME_MESSAGE = 'Welcome to the lamp control mode';
const WELCOME_REPROMT = 'If you new please say help'
const HELP_MESSAGE = 'In this skill you can controlling lamp to turn off or on, dim the lamp, change the lamp color and schedule the lamp';
const STOP_MESSAGE = 'Thanks for using this skill, Goodbye!';
const OFF_RESPONSE = 'Turning off the lamp';
const ON_RESPONSE = 'Turning on the lamp';
const DIM_RESPONSE = 'Dimming the lamp';
const CHANGE_RESPONSE = 'Changing the lamp color';
const AFTER_RESPONSE = 'Wanna control something again ?';
const handlers = {
'LaunchRequest': function () {
this.emit(':ask', WELCOME_MESSAGE, WELCOME_REPROMT);
},
'OnOffIntent' : function () {
var status = this.event.request.intent.slots.status.value;
var location = this.event.request.intent.slots.location.value;
console.log(status);
console.log(location);
if (status == 'on') {
// Promise Start
var mqttPromise = new Promise(function(resolve, reject) {
var options = {
port: '1883',
clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8),
username: 'username',
password: 'password',
};
var client = mqtt.connect('mqtt://broker-address', options)
client.on('connect', function() {
client.publish("lamp/status", status + ' ' + location, function() {
console.log("Message is published");
client.end();
resolve('Done Sending');
});
});
});
mqttPromise.then(
function(data) {
console.log('Function called succesfully', data);
this.emit(':ask', ON_RESPONSE, AFTER_RESPONSE);
}, function(err) {
console.log('An error occurred: ', err);
}
);
// Promise END
// this.emit(':ask', ON_RESPONSE, AFTER_RESPONSE);
// client.publish("lamp/status", status + ' ' + location);
} else if (status == 'off') {
this.emit(':ask', OFF_RESPONSE, AFTER_RESPONSE);
// client.publish("lamp/status", status + ' ' + location);
}
},
'DimIntent' : function () {
// to do here
},
'ChangeColorIntent' : function () {
// to do here
},
'ShceduleIntent' : function () {
// to do here
},
'AMAZON.HelpIntent': function () {
this.emit(':ask', HELP_MESSAGE, 'Wanna control something ?');
},
'AMAZON.StopIntent': function () {
this.emit(':tell', STOP_MESSAGE);
}
};
exports.handler = function (event, context, callback) {
const alexa = Alexa.handler(event, context, callback);
alexa.APP_ID = APP_ID;
alexa.registerHandlers(handlers);
alexa.execute();
}
I test my code with Service Simulator in Alexa Developer and get this result :
Result Image
So I checked output in Lambda and I got this error report :
Error in Lamda
Can anyone please help me? I have no idea with this because this is my first trial :)
The crux of your error seems to be this specific line in the log:
Cannot read property 'emit' of undefined
And after following the flow of your program, it's likely ocurring here:
mqttPromise.then(
function(data) {
console.log('Function called succesfully', data);
// It's probably ocurring in this line below
this.emit(':ask', ON_RESPONSE, AFTER_RESPONSE);
}, function(err) {
console.log('An error occurred: ', err);
}
)
The log is saying that you tried using this, it's undefined and doesn't have an emit property. Thats ocurring because of how this works in Js. You could workaround this problem by saving a reference to this
var that = this;
var mqttPromise = new Promise(function(resolve, reject) {
var options = {
port: '1883',
clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8),
username: 'username',
password: 'password',
};
var client = mqtt.connect('mqtt://broker-address', options)
client.on('connect', function() {
client.publish("lamp/status", status + ' ' + location, function() {
console.log("Message is published");
client.end();
resolve('Done Sending');
});
});
});
mqttPromise.then(
function(data) {
console.log('Function called succesfully', data);
that.emit(':ask', ON_RESPONSE, AFTER_RESPONSE);
}, function(err) {
console.log('An error occurred: ', err);
}
);
I would also recommend reading up a bit on "How 'this' works in Javascript"
MDN
Stack Overflow - "how does 'this' work"

Socket.io: emit from client does not work

I'm trying to emit an event on the client, but the server does not respond at all. A message does not appear in the console ('Received!'), the following event is not initiated. The event must emit when the button is clicked. Other actions, such as outputting a message to the console, work fine, but the event does not start. What is the problem? Сonnection events work properly.
Server:
class ChatHandlers {
constructor() {
this.names = {};
this.connection = this.connection.bind(this);
this.send = this.send.bind(this);
this.message = this.message.bind(this);
}
connection(socket) {
socket.emit('new_user', {
name: 'Example name'
});
}
send(socket) {
console.log('Received!');
var ip = socket.handshake.address;
io.sockets.emit('message', {
name: ip,
message: socket.message
});
}
message(socket) {
console.log('Success!');
}
}
var handlers = new ChatHandlers();
io.on('connection', handlers.connection);
io.on('send', handlers.send);
Client:
var socket = io.connect('http://localhost:8080/');
socket.on('connect', function (data) {
socket.on('new_user', function (data) {
console.log(data.name);
});
socket.on('message', function (data) {
console.log(data);
});
$('#send').click(function() {
socket.emit('send', {
message: $('#mess').val()
});
$('#mess').val('');
});

PeerJS peer not receiving data

I intend to use PeerJs to create P2P connections (data and later video).
I checked the tutorial and used the following code.
In browserA (Chrome 38):
var local;
var remote;
function peerJsInit() {
//listening host
local = new Peer(
{
key: 'myPeerJSKey'
});
local.on('connection', function(conn) {
alert('Connection is open');
conn.on('data', function(data) {
alert('Data: '+data);
});
});
}
function peerSend() {
remote = new Peer(
{
key: 'myPeerJSKey',
debug: true
});
var c = remote.connect('remoteId');
c.on('open', function() {
alert('connected');
c.send(' peer');
});
}
In browserB (Chrome 38):
var local;
var remote;
function peerJsInit() {
//listening host
local = new Peer({
key: 'myPeerJSKey'
});
local.on('connection', function(conn) {
alert('Connection is open');
conn.on('data', function(data) {
alert('Data: '+data);
});
});
}
function peerSend() {
remote = new Peer({
key: 'myPeerJSKey',
debug: true
});
var c = remote.connect('remoteId');
c.on('open', function() {
alert('connected');
c.send(' peer');
});
}
The Connection is open message showed, but the Data and connected messages never.
Can you tell me what I should change?
It seems that I forgot to add another callback.
It is sooo good that JS compiles without a problem, even when callbacks are missing... piece of g*rbage...
So instead of this:
local.on('connection', function(conn) {
alert('Connection is open');
conn.on('data', function(data) {
alert('Data: '+data);
});
});
I have to use this:
local.on('connection', function(conn) {
alert('Connection is open');
conn.on('open',function(){
conn.on('data', function(data) {
alert('Data: '+data);
});
});
});

Cannot send message using exchange in node-amqp

This is my code:
var amqp = require('amqp');
var connection = amqp.createConnection( { host: 'localhost' }, { defaultExchangeName: 'testexchange' });
connection.on('ready', function () {
console.log('Connected to rabbitmq');
var exchange = connection.exchange('testexchange', {confirm:true}, function(exch){
console.log('Created exchange: ' + exch.name);
var queue = connection.queue('testqueue', { durable: true }, function(q) {
exch.publish('testqueue', {a:1}, {}, function(error) {
console.log(error);
});
});
});
});
I'm using node 0.10.2 and node-amqp 0.1.6,
I can see textexchange by rabbitmqctl list_exchanges , but there's no testqueue by rabbitmqctl list_queues, what's wrong ?
You have to define it first.
connection.queue('testqueue', { durable: true })

Categories

Resources