publishing events to pubnub blocks from javascript client - block

I wanted to try out pubnub BLOCKS with a very contrived example.
Essentially, I'm publishing a simple message from a client (using javascript sdk) to see if the BLOCK that I've set (or i "think" i've set) to that respective channel is listening...contrived example is failing thus far...
Steps
Create an APP in pubnub to generate credentials.
Included pubnub SDK in simple HTML file, initialized Pubnub, set event listener, and publish/subscribe methods. Set channel to 'hello-world'
2a. Published/Subscribed to messages successfully from different browser windows with .
Went to pubnub debug console and set channel as 'hello-world' to see if messages from 'hello-world' channel would be broadcast and they were not.
From the client, I console logged the object that is returned from messages and the channel is appearing as 'hello-world'..so this left me wondering, why aren't i seeing the messages registered in the pubnub debug console in the same hello-world channel ?
Particularly, my question is: how can i send messages to a pubnub BLOCK from a pubnub CLIENT and send messages from a pubnub BLOCK to a pubnub CLIENT ? or in other words, pub/sub a BLOCK with a CLIENT using the Javascript SDK ?
The simple.js for hello-world example code:
(function(){
var pubnub = new PubNub({ publishKey : 'p-key', subscribeKey : 's-key' });
function $(id) { return document.getElementById(id); }
var box = $('box'), input = $('input'), channel = 'hello-world';
pubnub.addListener({
message: function(obj) {
box.innerHTML = (''+obj.message).replace( /[<>]/g, '' ) + '<br>' + box.innerHTML
}});
pubnub.subscribe({channels:[channel]});
input.addEventListener('keyup', function(e) {
if ((e.keyCode || e.charCode) === 13) {
pubnub.publish({channel : channel,message : input.value,x : (input.value='')});
}
});
})();

Publishing Messages and Events to PubNub BLOCKS from JavaScript
I've created an example below which sends messages to PubNub.
You can register a BLOCK on the hello-world channel to catch the message.
Register a BLOCK on PubNub. Make sure to start/deploy the block.
Update the publishKey and subscribeKey in the example below.
Run the example below.
(()=>{
'use strict';
// Initialize PubNub Socket SDK
const pubnub = new PubNub({
publishKey : 'demo'
, subscribeKey : 'demo'
});
// GUI Elements
const box = $('#messages')
, input = $('#message')
, submit = $('#submit')
, channel = 'hello-world';
// Open Socket to Channels
pubnub.subscribe({ channels : [channel] });
// When Messages Arrive
pubnub.addListener({ message: obj => receive_chat(obj) });
// When user sends chat
submit.click( event => send_chat(input.val()) );
input.keyup( event => {
if ((event.keyCode || event.charCode) === 13)
return send_chat(input.val());
});
// Draw Chat Messages on Screen
function receive_chat(obj) {
box.html((''+obj.message).replace( /[<>]/g, '' )+'<br>'+box.html());
}
// Send Chat Message
function send_chat(message) {
console.log(input.val());
pubnub.publish({ channel : channel, message : message });
input.val('');
return false;
}
})();
div, input { font-family: "Lucida Grande","Lucida Sans Unicode","Lucida Sans",Geneva,Arial,sans-serif; }
input { padding: 10px; margin: 10px; }
input[type=submit] { width: 100px; line-height: 100px; font-size: 20px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.pubnub.com/sdk/javascript/pubnub.4.4.3.min.js"></script>
<input id="message" placeholder="type your message">
<input id="submit" type="submit" value="Send">
<div id="messages"></div>

Related

stomp.js cannot receive message sent from pika (RabbitMQ version: 3.11.7)

I have a web page that should receive messages from RabbitMQ using STOMP:
<body>
<script src="stomp.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sockjs-client#1.1/dist/sockjs.min.js"></script>
<script>
var client = Stomp.client('ws://localhost:15674/ws');
client.debug = null;
var sub = function(d) {
// print_first(d.body);
console.log("got the message! ", d.body)
}
var on_connect = function(x) {
id = client.subscribe("/topic/test", sub);
console.log("connected")
};
var on_error = function() {
console.log('error');
};
client.connect('guest', 'guest', on_connect, on_error, '/');
</script>
</body>
when I run this code, it shows connected in the console (so far so good)
I also have a python backend, which should send messages to the queue (send.py):
import pika
connection = pika.BlockingConnection(
pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
channel.queue_declare("/topic/test")
properties = pika.BasicProperties(
content_type='application/json',
content_encoding='utf-8',
delivery_mode=2,
)
channel.basic_publish(exchange='',
routing_key='/topic/test',
body='Hello World!',
properties=properties)
The messages are sent (I ran the script with py -m send; the messages appear in the RabbitMQ Management) :
However the console.log in sub isn't running. Any idea how I can fix this?
Thanks!
Ended up using stomp.py instead of pika:
import stomp
PORT = 61613
LOCALHOST = '0.0.0.0'
conn = stomp.Connection11([(LOCALHOST, PORT)])
conn.connect('guest','guest')
conn.send(body="start",destination='/queue/test')
conn.send(body="end",destination='/queue/test')
conn.disconnect()

Resolving audio broadcasting error: client join failed DYNAMIC_KEY_EXPIRED (Agora.io)

I'm a server side developer with rudimentary JS knowhow. I'm tinkering with Agora's audio broadcasting functionality (specifically for the web). For reference, I've been following this: https://docs.agora.io/en/Audio%20Broadcast/start_live_audio_web?platform=Web
I'm attempting to broadcast audio as a host. I have an HTML button which fires a JS function where I:
Initialize a client
Set the role
Join a predefined channel
Publish a local stream
My understanding is that accomplshing the aforementioned will enable me to broadcast audio. When I try this, I end up getting a client join failed DYNAMIC_KEY_EXPIRED error. I'm unable to find documentation regarding how to resolve this. Can you help me resolve this? An illustrative example would be nice.
My JS code is below. Note that I'm using a temp token to test this functionality on localhost.
// rtc object
var rtc = {
client: null,
joined: false,
published: false,
localStream: null,
remoteStreams: [],
params: {}
};
// Options for joining a channel
var option = {
appID: "anAppID",// from 'Project Management' dashboard
channel: "AudioLive",
uid: null,//The user ID should be unique in a channel. If you set the user ID as null or 0, the Agora server assigns a user ID and returns it in the onSuccess callback.
token: "aTempToken"// TEMP Token
}
function createBroadcast(role) {
console.log("entered createBroadcast");
// Create a client
rtc.client = AgoraRTC.createClient({mode: "live", codec: "h264"});
// Initialize the client
rtc.client.init(option.appID, function () {
console.log("init success");
// Note: in a live broadcast, only the host can be heard and seen. You can also call setClientRole() to change the user role after joining a channel.
rtc.client.setClientRole(role);
console.log("role is set");
// Call Client.join in the onSuccess callback of Client.init
rtc.client.join(option.token ? option.token : null, option.channel, option.uid ? +option.uid : null, function (uid) {
console.log("join channel: " + option.channel + " success, uid: " + uid);
rtc.params.uid = uid;
// Call AgoraRTC.createStream to create a stream in the onSuccess callback of Client.join
rtc.localStream = AgoraRTC.createStream({
streamID: rtc.params.uid,
audio: true,
video: false,
screen: false,
})
// Call Stream.init to initialize the stream after 'creating' the stream above
// Initialize the local stream
rtc.localStream.init(function () {
console.log("init local stream success");
// play stream with html element id "local_stream"
rtc.localStream.play("local_stream");
// Call Client.publish in the onSuccess callback of Stream.init to publish the local stream
// Publish the local stream
rtc.client.publish(rtc.localStream, function (err) {
console.log("publish failed");
console.error(err);
})
}, function (err) {
console.error("init local stream failed ", err);
});
}, function(err) {
console.error("client join failed", err)
})
}, (err) => {
console.error(err);
});
}
<div style="background:#f0f3f4;padding:20px">
<button id="broadast" style="height:40px;width:200px" onclick="createBroadcast('host')">Start Live Broadcast</button>
</div>
I've not added the actual values for appID and token in the code above.
Note: Please ask for more information in case you require it.
The error that you are facing is due to the expiry of the token generated for authentication purposes while generating an APP ID. To resolve this you will have to generate a new token as elaborated in the below given links:
Token-expired
renewToken
A token (or a temporary token) expires after a certain period of time. When the SDK notifies the client that the token is about to expire or has expired by the onTokenPrivilegeWillExpire or onTokenPrivilegeDidExpire callbacks, you need to generate a new token and call the renewToken method.
client.on("onTokenPrivilegeWillExpire", function(){
//After requesting a new token
client.renewToken(token);
});
client.on("onTokenPrivilegeDidExpire", function(){
//After requesting a new token
client.renewToken(token);
});
Include the above functions in your javascript code along with the rest of the eventListeners.
Incase your application doesn't require security you can opt to not use a token and generate an App ID without a certificate.
App ID without certificate
Do get back for further support incase the issue remains unresolved.

How to read from AzureIOT only messages from one device

I have an Azure IOT solution where data from 2 devices go to the same IOT hub. From my computer I need to read the messages only from one of the devices. I implemented the ReadDeviceToCloudMessages.js in https://learn.microsoft.com/en-us/azure/iot-hub/iot-hub-node-node-getstarted
var client = EventHubClient.fromConnectionString(connectionString);
client.open()
.then(client.getPartitionIds.bind(client))
.then(function (partitionIds) {
return partitionIds.map(function (partitionId) {
return client.createReceiver('todevice', partitionId, { 'startAfterTime' : Date.now()}).then(function(receiver) {
console.log('Created partition receiver: ' + partitionId)
receiver.on('errorReceived', printError);
receiver.on('message', printMessage);
});
});
})
.catch(printError);
But I am getting all the messages in the IOThub. How do I get messages only from one device.
You can route the expected device message to build-in endpoint: events. Then you can only receive the selected device message from your above code.
Create the route:
Turn "Device messages which do not match any rules will be written to the 'Events (messages/events)' endpoint." to off and make sure the route is enabled.

Can't get GCM push messages being sent properly

So my GCM push message works if I use this test link
http://www.androidbegin.com/tutorial/gcm.html
Here's the response
{ "multicast_id":7724943165862866717,
"success":1,
"failure":0,
"canonical_ids":0,
"results":[{"message_id":"0:1418649384921891% 7fd2b314f9fd7ecd"}]}
However if I push using my own service using node push service using the toothlessgear/node-gcm lib
https://github.com/ToothlessGear/node-gcm I get a success message on the server but no msg makes it to the client
{ multicast_id: 5130374164465991000,
success: 1,
failure: 0,
canonical_ids: 0,
results: [ { message_id: '0:1418649238305331%7fd2b3145bca2e79' } ] }
I also tried the same message using pushwoosh and push woosh doesn't work either. How come I'm getting a success message on the server, but no push is received on the client on the latter two services. Is there some sort of ip configuration that I need to do, or some sort of certificate? I've used the same google api server key which is open to all ips on all 3 of these services.
Why does the response show success on the latter but no msg gets received on the client?
Node service server side code
var gcm = require('node-gcm');
// create a message with default values
var message = new gcm.Message();
// or with object values
var message = new gcm.Message({
collapseKey: 'demo',
delayWhileIdle: true,
timeToLive: 3,
data: {
key1: 'message1',
key2: 'message2'
}
});
var sender = new gcm.Sender('insert Google Server API Key here');
var registrationIds = ['regId1'];
/**
* Params: message-literal, registrationIds-array, No. of retries, callback-function
**/
sender.send(message, registrationIds, 4, function (err, result) {
console.log(result);
});
So the pushes were correctly being sent, my issue was with the cordova plugin on the client which requires that the android payload for "message" or "title" be set. The sample php just coincidentally was setting the message property and that's why it worked.
Updating the code to add the following to the data
data: {message:'test'}
works correctly

instant messaging with intel xdk receiving notification on new message

i would like to create instant messaging in cross platform. how can i get the application keep listening to the server so when there is a message coming, the application could receive a notification.
maybe like service in android?
I've read about push message (push mobi) but it doesn't seem to meet my need since it blast the notification on all registered id from admin panel, not from 1 id to another id.
i notice GCM but some say it is not suitable for sending and receiving chat.
Sounds like a good scenario for websockets. There's a phongap plugin for android that will allow you to use them.
Take a look at the plugin demo. It looks pretty strait-forward.
client side javascript:
var socket = io.connect("http://10.0.2.2:8080");
document.getElementById('log').innerHTML = "connecting";
socket.on('ping', function (data) {
document.getElementById('log').innerHTML = data.message;
socket.emit('pong', { message: 'Hello from client!' });
});
socket.on('connect', function () {
document.getElementById('log').innerHTML = "connected";
});
});
Server side web service in node.js:
var io = require('socket.io').listen(8080);
io.sockets.on('connection', function (socket) {
console.log('emit...');
socket.emit('ping', { message: 'Hello from server ' + Date.now() });
socket.on('pong', function (data) {
console.log(data.message);
});
});
console.log('listening on port 8080');