pusher gives no call back - javascript

I am trying to test a basic pusher trigger event that gives me a simple alert and a console log, but it wont work. The response is received from the pusher console debug but there are no alerts. I am using laravel 5.3 and its routes and a view for this. Below is my code. I have censored the sensitive information.
route file web.php
Route::get('/bridge', function() {
error_reporting(E_ALL);
$options = array(
'cluster' => 'ap1',
'encrypted' => true
);
$pusher = new Pusher(
'key censored',
'secret censored',
'app id censore',
$options
);
$data['message'] = 'hello world';
$pusher->trigger('test_channel', 'my_event', $data);
return view('pusher');
});
and view pusher.blade.php
<!DOCTYPE html>
<head>
<title>Pusher Test</title>
<script src="https://js.pusher.com/3.2/pusher.min.js"></script>
<script>
// Enable pusher logging - don't include this in production
Pusher.logToConsole = true;
var pusher = new Pusher('e5bbf707214a6223d044', {
cluster: 'ap1',
encrypted: true
});
var channel = pusher.subscribe('test_channel');
channel.bind('my_event', function(data) {
alert(data);
console.log(data);
});
</script>
</head>
chrome console gives me the following logs.
Pusher : State changed : initialized -> connecting
Pusher : Connecting : {"transport":"ws","url":"wss://ws-ap1.pusher.com:443/app/censored key?protocol=7&client=js&version=3.2.2&flash=false"}
Pusher : State changed : connecting -> connected with new socket ID 5034.8700909
Pusher : Event sent : {"event":"pusher:subscribe","data":{"channel":"test_channel"}}
Pusher : Event recd : {"event":"pusher_internal:subscription_succeeded","data":{},"channel":"test_channel"}
Pusher : No callbacks on test_channel for pusher:subscription_succeeded

You created a binding for the my_event event. This error is complaining that you don't have a callback for the pusher:subscription_succeeded event. If you want to catch that and handle it, you need to create a binding.
https://pusher.com/docs/client_api_guide/client_presence_channels#pusher-subscription-succeeded
channel.bind('pusher:subscription_succeeded', function(members) {
alert('successfully subscribed!');
});

This worked for me
channel.bind('pusher:subscription_succeeded', function(members) {
// alert('successfully subscribed!');
});
channel.bind("App\\Events\\NewMessage", function(data) {
console.log(data);
});

Related

Same message in sender and receiver chat in pusher.js php

I am new to PusherJS and developing a real-time chat app using PHP. Everything working fine but when I press enter to send message, it append it in sender's box and into receiver's box also. How I can differentiate it on the basis of session or user_id. See there are same message is sender and receiver's box:
Real-Time.php:
$options = array(
'cluster' => 'ap2',
'useTLS' => true
);
$pusher = new Pusher\Pusher(
'c575a7********edb87d',
'8fee27********57fdd2',
'7***6*',
$options
);
$pusher->trigger('channel', 'event', $data);
The .js file:
var pusher = new Pusher('c575a76********db87d', {
cluster: 'ap2',
forceTLS: true
});
var channel = pusher.subscribe('channel');
channel.bind('event', function(data) {
var msg_template = ``; //<-- Just removed template it's simple HTML
$("ul#messages").append(msg_template);
});
You need to restrict the message sender from receiving the broadcasted message. How to do so is documented at on the Pusher website.
First, you need to store the SocketID when connecting to Channels:
var pusher = new Pusher('APP_KEY');
var socketId = null;
pusher.connection.bind('connected', function() {
socketId = pusher.connection.socket_id;
});
Once this has been found, you can use it in the event sent to the server:
data: {
id: 'some_id',
updated_value: 'some_value',
socket_id: socketId // pass socket_id parameter to be used by server
}
This will then prevent the client with that socketId from receiving the message.

Pubnub.subscribe not working

I am trying to implement a simple chat in my AngularJs 1.4.5 web app using pubnub.
I am following the steps as given in the pubnub tutorial.
$scope.channel = 'chat_for_trial';
$scope.uuid = 'user1';
Pubnub.init({
publishKey: 'demo',
subscribeKey: 'demo',
uuid: $scope.uuid
});
// Send the messages over PubNub Network
$scope.messageContent = {message: ''};
$scope.sendMessage = function() {
// $scope.messageContent = data;
// Don't send an empty message
if (!$scope.messageContent.message || $scope.messageContent.message === '') {
return;
}
Pubnub.publish({
channel: $scope.channel,
message: {
content: $scope.messageContent.message,
sender_uuid: $scope.uuid,
date: new Date()
},
callback: function(m) {
console.log(m);
}
});
// Reset the messageContent input
$scope.messageContent.message = '';
};
//get messages
$scope.messageContent.messages = [];
// Subscribing to the ‘messages-channel’ and trigering the message callback
Pubnub.subscribe({
channel: $scope.channel,
triggerEvents: ['callback']
});
// Listening to the callbacks
$scope.$on(Pubnub.getMessageEventNameFor($scope.channel), function (ngEvent, m) {
$scope.$apply(function () {
console.log("i am here")
$scope.messageContent.messages.push(m)
});
});
I can send message to the channel chat_for_trial but when checking the occupancy in pubnub console, the subscribed uuid is not listed.
When I sending the message from console it is not displayed in the web app. But data sent from web app can be seen in the pubnub console.
I am working with pubnub: 4.20.1, pubnub-angular: 4.1.0, angularjs: 1.4.5
I would like to know what I am missing here.
The issue was due to the mismatch of the pubnub and pubnub-angular version from the tutorial and the one installed using bower in my application.
The tutorial was for sdk v3 and the current sdk version v4.
Refer this link for working with pubnub sdk v4.

Pusher : No callbacks on test for pusher for my event

so i am trying to get this test where i get each object i create, broadcasted without refreshing the page.
Here is the js where we instantiate pusher and bind the event for UserHasRegistered:
// Enable pusher logging - don't include this in production
Pusher.logToConsole = true;
(function() {
var pusher = new Pusher('3c50750503376de6d201', {
cluster: 'eu',
encrypted: true
});
var channel = pusher.subscribe('test');
channel.bind('App\\Events\\UserHasRegistered', function(data) {
console.log(data);
});
})();
</script>
This is the route where i broadcast a registered user name, wich i also mention in the binding to pusher.
Route::get('broadcast', function(){
$name = Request::input('name');
event(new UserHasRegistered($name));
return 'Done';
});
The event Listener is working, i got the env setup as well as the broadcast.php, but this is what i get:
Pusher : State changed : initialized -> connecting pusher.min.js:8:2561
Pusher : Connecting : {"transport":"ws","url":"wss://ws-eu.pusher.com:443 /app/3c50750503376de6d201?protocol=7&client=js&version=4.1.0&flash=false"} pusher.min.js:8:2561
Pusher : State changed : connecting -> connected with new socket ID 123754.768449 pusher.min.js:8:2561
Pusher : Event sent : {"event":"pusher:subscribe","data":{"channel":"test"}} pusher.min.js:8:2561
Pusher : Event recd : {"event":"pusher_internal:subscription_succeeded","data":{},"channel":"test"} pusher.min.js:8:2561
Pusher : No callbacks on test for pusher:subscription_succeeded pusher.min.js:8:2561
You should use both. To catch the error and subscribe to your channel:
channel.bind('pusher:subscription_succeeded', function(members) {
// alert('successfully subscribed!');
});
channel.bind("App\\Events\\UserHasRegistered", function(data) {
console.log(data);
});
Since you can bind to more than one event.

Pusher - Private channel subscription

I have a code with subscribe private channels, and when I try make a subscription I have the next message:
Pusher : Couldn't get auth info from your webapp : 404
Scenario:
Javascript(Sencha touch) and PHP(Laravel)
The subscription is in javascript:
Pusher.channel_auth_endpoint = "/pusher.php";
var APP_KEY = '4324523452435234523';
var pusher = new Pusher(APP_KEY);
var channel = pusher.subscribe('private-l2');
channel.bind('pusher:subscription_succeeded', function() {
alert("ahora siiii");
});
// for debugging purposes. Not required.
Pusher.log = function(msg) {
if(window.console && window.console.log) {
window.console.log("PUSHER LOG: "+msg);
}
}
AND the pusher.php / LARAVEL
$this->app_id = '66981';
$this->app_key = '4324523452435234523';
$this->app_secret = 'f34632459911e2670dcf';
$pusher = new Pusher($this->app_key, $this->app_secret, $this->app_id);
$auth = $pusher->socket_auth(Input::get('channel_name'), Input::get('socket_id'));
echo $auth;
The result is the error:
Pusher : State changed : connecting -> connected
Pusher : Couldn't get auth info from your webapp : 404
You should set up a route for the Pusher authentication
Route::post('pusher/auth', 'ApiController#pusherAuth');
In that method you should first disable php debugbar (if you're using it) authenticate the user and if authentication checks, then return the response.
I'll paste my controller code below.
public function pusherAuth()
{
\Debugbar::disable();
$user = auth()->user();
if ($user) {
$pusher = new \Pusher(config('broadcasting.connections.pusher.key'), config('broadcasting.connections.pusher.secret'), config('broadcasting.connections.pusher.app_id'));
echo $pusher->socket_auth(request()->input('channel_name'), request()->input('socket_id'));
return;
}else {
header('', true, 403);
echo "Forbidden";
return;
}
}
My JS code:
var pusher = new Pusher(project.pusherKey, {
cluster: 'eu',
encrypted: true,
authEndpoint: apiUrl(['pusher', 'auth']), // just a helper method to create a link
auth: {
headers: {
'X-CSRF-Token': project.token // CSRF token
}
}
});
var channelName = 'private-notifications-' + project.userId; // channel for the user id
var channel = pusher.subscribe(channelName);
channel.bind('new_notification', function (data)
{
app.addNotification(data); // send the notification in the JS app
});
I hope this helps.
Cheers!
Private Pusher channels require the client to authenticate for access. See http://pusher.com/docs/authenticating_users for details on configuring the client for authentication and setting up an authentication endpoint.
Change
Pusher.channel_auth_endpoint = "/pusher.php";
for:
Pusher.channel_auth_endpoint = "/public/broadcasting/auth";
I am not expert at laravel but I guess you have used get request to retrieve data(Socket id & channel name) while it's the post request from pusher server to your server endpoint. Use post to retrieve the data.

How to reconnect after you called .disconnect()

Question: How do you reconnect a client to the server after you have issued a manual .disconnect()?
In my current project, I need to disconnect a client from the server when the user log out from the session. I did a socket.disconnect() to do the disconnection successfully. Server removed the user from the session.
After awhile, the user decided to login again, but socket.io refuses to connect.
I am clear that Socket.IO has implemented reconnection algorithm but clearly this is a different case.
Below is the piece of code where I do the connection. On second trigger of this block of code, object socket was created, but no connect was fired from this object.
//Start the socket
var socket = io.connect(SOCKET_IO_URL);
socket.on('connect', function() {
me.fireEvent('connect');
socket.emit('register', {
hashed_identifier: hashed_identifier,
account_id: account_id
});
});
socket.on('ready', function() {
me.ready = true;
me.log('Handshake done. Listening for new data');
});
socket.on('data', function(data) {
me.fireEvent('data', data);
//Tells server we received it
socket.emit('data', {ack: 1});
});
socket.on('disconnect', function() {
me.fireEvent('disconnect');
});
UPDATE: As requested by #Tony
In fact the whole thing is wrapped under Sencha Touch 2.0, but I believe there is nothing to do with ST2.0
This is my Data Class. Usage of this class is when the user logged in, this class will get initialized. And upon the user logout, the system will call the disconnect() method in this class.
When the user login again, this class is initialized again, but funny is the socket somehow retained all the previous events and sessions it has previously.
/**
* Serve as interface to wait for data communication in between server and client
*/
Ext.define('go.module.connect.Data', {
mixins: {
observable: 'Ext.mixin.Observable'
},
config: {
account: null
},
ready: false,
socket: null,
constructor: function(cfg) {
var me = this,
hashed_identifier = Sha1.hash(go.__identifier);
me.initConfig(cfg);
var account_id = me.getAccount().get('id');
//Start the socket
var socket = io.connect(SOCKET_IO_URL);
socket.on('connect', function() {
console.log('connect');
me.fireEvent('connect');
socket.emit('register', {
hashed_identifier:hashed_identifier,
account_id: account_id
});
});
socket.on('ready', function() {
me.ready = true;
me.log('Handshake done. Listening for new data');
});
socket.on('data', function(data) {
me.fireEvent('data', data);
//Tells server we received it
socket.emit('data', {ack: 1});
});
socket.on('disconnect', function() {
me.fireEvent('disconnect');
});
console.log(socket);
if (!socket.socket.connected){
socket.socket.reconnect();
}
me.socket = socket;
me.callParent([cfg]);
},
disconnect: function() {
this.socket.disconnect();
this.socket.removeAllListeners();
this.socket.socket.removeAllListeners();
},
log: function(msg) {
console.log('## Connect: '+msg);
}
});
And below is my console.log results:
And below is my node.js debug window
I believe the root cause of this funny scenario is that the previously attached connect event listener is not removed thoroughly. How should I remove it? Should I use once? or I should specify the listener function as well. I thought removeAllListeners() is sufficient for this task.
The standard approach in latest socket.io is:
socket.on('disconnect', function() {
socket.socket.reconnect();
})
This is what I've been using in my app and works great. It also ensures that the socket keeps trying to reconnect if the server goes way, and eventually reconnects when the server is back online.
In your case, you need to ensure two things:
You create your socket only once. Don't call socket = io.connect(...) more than once.
You setup your event handling only once - otherwise they will be fired multiple times!
So when you want to reconnect the client, call socket.socket.reconnect(). You can also test this from the browser console in FireFox and Chrome.
You can reconnect by following client side config.
// for socket.io version 1.0
io.connect(SERVER_IP,{'forceNew':true };
I'm doing this way with socket.io 1.4.5 and it seems to work, for now:
var app = {
socket: null,
connect: function() {
// typical storing of reference to 'app' in this case
var self = this;
// reset the socket
// if it's not the first connect() call this will be triggered
// I hope this is enough to reset a socket
if( self.socket ) {
self.socket.disconnect();
delete self.socket;
self.socket = null;
}
// standard connectiong procedure
self.socket = io.connect( 'http://127.0.0.1:3000', { // adapt to your server
reconnection: true, // default setting at present
reconnectionDelay: 1000, // default setting at present
reconnectionDelayMax : 5000, // default setting at present
reconnectionAttempts: Infinity // default setting at present
} );
// just some debug output
self.socket.on( 'connect', function () {
console.log( 'connected to server' );
} );
// important, upon detection of disconnection,
// setup a reasonable timeout to reconnect
self.socket.on( 'disconnect', function () {
console.log( 'disconnected from server. trying to reconnect...' );
window.setTimeout( 'app.connect()', 5000 );
} );
}
} // var app
app.connect();
socket.socket.connect();
gets you reconnected.
It seems to me it is how you handle the disconnect...
Worked for me using socket.io - v1.1.0
wrong way...
var sock = io( '/' );
sock.on( 'connect', function(x) { console.log( 'Connected', x ); } );
// now we disconnect at some point:
sock.disconnect();
// now we try to reconnect...
sock.connect()
// or
sock.reconnect();
// - both seem to create the new connection in the debugger, all events are missing though
correct way...
// As above with 3 extra characters, everything functions as expected...
//events fire properly...
sock.io.disconnect();
// consequently i'm also using (for consitency)
sock.io.reconnect();
// sock.connect() still seems to work however.
socket.io v2.0 (current)
For the peoples that was looking as me for the last version please find the doc extract as below:
To manually reconnect:
socket.on('disconnect', () => {
socket.open();
});
socket.io-client v2.2.0
import io from "socket.io-client"
var socket = io(url) // initial connection
const reconnect = () => {
if(!socket.connected) {
socket = io(url) // reconnects to a new socket
}
}

Categories

Resources