Unable to receive messages in browser client - node.js

I'm unsuccessfully attempting to create an pub-sub instant messaging service. I am unable to receive messages in browser client.
The following code is from my client1.html file. I believe the trouble I'm having relates to the client unsuccessfully subscribing to '/channel'. I've added the alerts and am receiving the 'BEFORE & AFTER' but not the 'DURING' and the message.text is not appearing on the console. Any thoughts as to why a client cannot see the messages on the browser would be appreciated.
var client = new Faye.Client('/faye',{
timeout: 20
});
alert("BEFORE client subscription");
client.subscribe('/channel', function(message) {
$('#messages').append('<p>' + message.text + '</p>');
alert("DURING client subscription");
console.log(message.text);
});
alert("AFTER client subscription");
The browser console repeats the following error repeatedly:
POST http://my.server#server:8000/faye 404 (Not Found)
This error points to 'faye-browser.js:2023' which refers to the following line:
xhr.send(Faye.toJSON(message));
EDIT
This is is the server.js file
var fs = require("fs");
var config = JSON.parse(fs.readFileSync("config.json"));
var host = config.host;
var port=config.port;
var express = require("express");
var Faye = require('faye');
var bayeux = new Faye.NodeAdapter({mount: '/faye', timeout:45});
var app = express();
app.configure(function(){
app.use(express.bodyParser());
app.use(express.static('/'+__dirname));
});
app.post('/message', function(request, response){
bayeux.getClient().publish('/channel', {text:request.body.message});
console.log('broadcast message:' + request.body.message);
response.send(200);
});
bayeux.attach(app);
app.listen(port);

I've just configured Faye for our application, you are doing
bayeux.attach(app);
app.listen(port);
did not work for me, what worked is this
bayeux.attach(app.listen(port, function() {}));
I also think that you should use the whole url when you are creating Faye, not just the final part, like so:
var client = new Faye.Client('http://my.url.com/faye', { timeout: 20 });

Related

Twilio 11200 HTTP retrieval failure with Node app on Heroku

My Node.js app is set to respond to a text message received at a paid Twilio number. I tested it using ngrok and everything worked fine. Once I deployed the app to Heroku, however, I started seeing an 11200 HTTP retrieval failure error in the Twilio console.
Are there configuration settings in Heroku that I need to set up?
// Twilio Credentials
const accountSid = 'xxx';
const authToken = 'xxx';
const client = require('twilio')(accountSid, authToken);
const MessagingResponse = require('twilio').twiml.MessagingResponse;
var express = require('express');
var app = express();
var bodyparser = require('body-parser');
app.use(bodyparser.urlencoded({extended: true}));
app.set('port', (process.env.PORT || 3000));
app.use('/', function(request, response){
response.send();
});
app.post('/sms', function(req, res) {
const twiml = new MessagingResponse();
twiml.message('Hi, this is Culpability. Your incident has been logged. Your
unique id # XXXX');
res.writeHead(200, {'Content-Type': 'text/xml'});
res.end(twiml.toString());
});
app.listen(app.get('port'), function() {
// console.log('Node app is running on port', app.get('port'));
});
Twilio developer evangelist here.
I think the problem is mostly in the method you are using to send the response. Currently your final line of the /sms route is res.end(twiml.toString()); however Response#end is used "to quickly end the response without any data."
I think your use of res.writeHead() might be outdated now too.
I would change your /sms route to something like this:
app.post('/sms', function(req, res) {
const twiml = new MessagingResponse();
twiml.message('Hi, this is Culpability. Your incident has been logged. Your unique id # XXXX');
res.set('Content-Type', 'text/xml');
res.status(200).send(twiml.toString());
});
Then try redeploying to Heroku and see what happens.

Connecting Flash to Node via websockets - Crossdomain.xml issue

I am trying to set up a simple websocket server that communicates between a Flash AS3 client and a Node.js backend. The following code is when both the client and server are hosted locally. The code also functions properly when the swf is hosted locally connected to the server hosted on heroku. The socket only fails when both the swf and the server are hosted online.
Node.js Code (Server)
var WebSocketServer = require("ws").Server
var net = require('net');
var http = require("http")
var express = require("express")
var app = express()
var crossdomain = require('crossdomain')
var port = process.env.PORT || 5000;
app.use(express.static(__dirname + "/"))
var xml = crossdomain({ domain: '*' });
app.all('/crossdomain.xml', function (req, res, next) {
res.writeHead(200, { 'Content-Type': 'application/xml; charset=utf-8' });
res.write(xml);
//res.write(new Buffer([0x00]))
res.end();
});
var server1 = http.createServer(app)
server1.listen(port)
console.log("http server listening on " + port)
var wss = new WebSocketServer({server: server1})
wss.on("connection", function(ws) {
console.log("Connected");
ws.on("close", function() {
console.log("websocket connection close")
})
})
Crossdomain file - example.com/crossdomain.xml
<cross-domain-policy>
<allow-http-request-headers-from domain="*" headers="*"/>
<site-control permitted-cross-domain-policies="all"/>
<allow-access-from domain="*" secure="false"/>
</cross-domain-policy>
AS3 Code (Client) - I'm Using (https://github.com/theturtle32/AS3WebSocket)
import com.worlize.websocket.*;
Security.loadPolicyFile("http://example.com/crossdomain.xml");
var websocket:WebSocket = new WebSocket("ws://example.com", "*", "echo-protocol");
websocket.addEventListener(WebSocketEvent.OPEN, handleWebSocketOpen);
websocket.connect();
var con = false;
function handleWebSocketOpen(event:WebSocketEvent):void {
trace(event);
}
When the client is accessed from the server a request for the crossdomain.xml does occur and it gets returned successfully to the client, but at that point nothing happens anymore. I've been trying to solve this for ages with no luck. I did find that when you return the crossdomain file you need to end it with a 0x00 for it to be properly read, but I haven't found a way to make to that work. I've tried adding res.write(new Buffer([0x00])) to the response from the crossdomain request as well as several other modifications to no avail. These all seem to stop the xml file from being valid anyway.
I would greatly appreciate if anyone could help in getting this to work, I've been struggling with it for an extremely long time and can't quite seem to get this last step working.

Faye web socket

I'm new with faye web socket, and I tried to set up a server and a client to exchange information. Unfortunately I'm missing something and I can't get on the client the messages sent from the server.
This is my server.js:
var faye = require('faye');
var Router = require('node-simple-router');
var router = new Router();
var server = require('http').createServer(router);
var port = 5000;
var bayeux = new faye.NodeAdapter({mount: '/faye/calls'});
bayeux.attach(server);
// Launch the server
server.listen(port, function() {
console.log('Listening on ' + port);
setInterval(function(){
bayeux.getClient().publish('/faye/calls', {text: 'Hello'});
},3000);
And is my client.js
var faye = require('faye');
var client = new faye.Client('http://localhost:5000/faye', {
timeout: 600,
retry: 5
});
var sub = client.subscribe('/calls', function(message) {
console.log('message:' + message);
});
sub.then(function() {
console.log('overall Subscription is now active!');
});
Can somebody please tell me what I'm missing?
Thanks very much
Have a good day
It looks like your paths are to blame:
var bayeux = new faye.NodeAdapter({mount: '/faye/calls'});
should mount to /faye:
var bayeux = new faye.NodeAdapter({mount: '/faye'});
and
bayeux.getClient().publish('/faye/calls', {text: 'Hello'});
Should actually publish to /calls
bayeux.getClient().publish('/calls', {text: 'Hello'});
That appears to resolve the issue for me:
overall Subscription is now active!
message:[object Object]
message:[object Object]
message:[object Object]

node-amqp + rabbitMQ how to convert post request into message

I have express server setup to listen post request and put the post request in message queue
var express = require('express');
var app = express();
app.use(express.bodyParser());
app.post('/test-page', function(req, res) {
var amqp = require('amqp');
var connection = amqp.createConnection({url: "amqp://guest:guest#localhost:5672"},{defaultExchangeName: ''});
connection.on('ready',function(){
console.log('connected');
var messageToSend = req.body;
var queueToSendTo = "xyz";
connection.queue(queueToSendTo,{'passive': true},function(){
connection.publish(queueToSendTo, messageToSend);
res.send(200);
connection.end();
});
});
});
app.setMaxListeners(0);
app.listen(80);
The above code is suppose to collect the post request and put in queue, If I send 10 requests, there would be more than 300 messages in queue. I don't understand this behaviour or may be my understanding of putting 'publish' call in 'ready' function is wrong since the 'connected' log message in above code is printed more than 10 for 10 post request.
Is it happening due to 'connection.end' not closing the connection?
I want to have each post request converted to a message in RabbitMQ,
Please advise if there is any better way.
(I am using latest master of node-amqp with rabbit-server-3.1.4-1 on ubuntu 12.04)
The issue it's that you are creating a connection to the queue for every post request to test-page. So you have to create this connection outside of the post handler.
I haven't tested the code but this should do the trick:
var express = require('express');
var app = express();
app.use(express.bodyParser());
var amqp = require('amqp');
var connection = amqp.createConnection({url: "amqp://guest:guest#localhost:5672"},{defaultExchangeName: ''});
connection.on('ready', function() {
console.log('connected');
});
app.post('/test-page', function(req, res) {
var messageToSend = req.body;
var queueToSendTo = "xyz";
connection.publish(queueToSendTo, messageToSend);
res.send(200);
});
app.setMaxListeners(0);
app.listen(80);

Socket.io will not work

I have changed my files to look as shown below. The javascript console shows nothing and the web page shows nothing. Just a blank screen. Does anybody know of a web site which uses socket.io. I would like to inspect the code to see how they do it since none of the examples on the socket.io page work for me. Does anybody know if extra ports need to be allowed in the iptables file?
Using the Chrome browser, if I goto the javascript console and goto the Network tab I get successes but the last call says Pending ??? It looks like it is hung. Could this be a firewall issue?
/socket.io/1/websocket
GET
101
Switching Protocols
Pending
Other
127 B
0 B
Pending
it is Pending in selector.js on line 168:
document.body.appendChild(menuDiv);
Maybe this is why I am not seeing anything? It is properly serving up socket.io/socket.io.js
Files below:
//app.js
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
app.use(express.static(__dirname + '/public'));
var port = 80;
var io = require('socket.io').listen(server, {
log : false
});
io.sockets.on('connection', function(socket) {
socket.on('hi', function(data) {
console.log('yay');
socket.emit('hello');
});
});
server.listen(port);
public/index.html
//index.html
<script src="http://localhost/socket.io/socket.io.js"></script>
<script>
var chat = io.connect('http://localhost/chat')
, news = io.connect('http://localhost/news');
chat.on('connect', function () {
chat.emit('hi');
});
chat.on('hello',function(){
console.log('yay got hello');
});
var socket = io.connect('http://localhost:80');
socket.on('connect', function () {
chat.emit('hi');
});
socket.on('hello',function(){
console.log('yay got hello');
});
</script>
You're using namespaces news and chat even though your server doesn't implement them correctly.
You javascript connection should look like this instead:
var socket = io.connect('http://localhost:80');
socket.on('connect', function () {
chat.emit('hi');
});
socket.on('hello',function(){
console.log('yay got hello');
});

Resources