How do I separate the code of publish and subscribe as Client.js and Server.js code? Also, how do I print the message on browser and not in console? Do I really need to use web sockets to push data to browser? like: Send message from Node.js Server to Client via function call
how do I pass it in routes:
router.get('/api', function(req, res, next) {
res.render('index', { data: data });
});
app.js
var main = require("./server");
server.js
var http = require("http");
var fs = require("fs");
var PubNub = require("pubnub");
var connect = require("connect");
function server404Response (response) {
response.writeHead(404,{'contentType':'text/plain'});
response.write("404, Page Not Found Error");
response.end();
}
function onRequest(request,response) {
if(request.method == 'GET' && request.url == '/'){
publish();
response.writeHead(200,{'contentType':'text/html'});
fs.createReadStream("./index.html").pipe(response);
}else{
server404Response(response);
}
}
http.createServer(onRequest).listen(8888);
console.log("Server is running");
function publish() {
pubnub = new PubNub({
publishKey : 'pub-key',
subscribeKey : 'sub-key'
})
var publishConfig = {
channel : "test",
message : "Hello from PubNub Docs!"
}
pubnub.addListener({
status: function(statusEvent) {
if (statusEvent.category === "PNConnectedCategory") {
pubnub.publish(publishConfig);
}
},
message: function(message) {
console.log("New Message!!", message);
},
presence: function(presenceEvent) {
// handle presence
}
})
//if I add subscribe code here. it just works fine
};
client.js
var PubNub = require("pubnub");
pubnub = new PubNub({
publishKey : 'pub-key',
subscribeKey : 'sub-key'
})
console.log("Subscribing..");
pubnub.subscribe({
channels: ['test']
});
via Murlidhar Fichadia
No comments:
Post a Comment