I'm newbie in Nodejs. I'm writing a program that use Primus to comunicate client and server. But I can't send message from server to client. Here is my code. Client:
<html>
<head>
<title> hung </title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="primus/primus.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("input#button").click(function(){
var content = $("#content").val();
$.ajax({
type:"POST",
url:"http://node-xxx.rhcloud.com/api/sendmessage",
data:{"data": content},
success: function(result){
alert(result);
}
});
});
});
</script>
</head>
<body>
<textarea name="content" id="content" ></textarea>
<input type="button" id="button" value="OK">
<div id="message"></div>
<script>
var primus;
if (primus) primus.end();
primus = new Primus();
primus.on('open', function open() {
log('open', 'Open', 'The connection has been established.');
document.getElementById('connect').innerHTML = 'connected';
});
primus.on('data', function incoming(data) {
alert(data);
});
primus.on('end', function end() {
log('end', 'End', 'The connection has ended.');
});
primus.on('close', function end() {
log('close', 'close', 'We\'ve lost the connection to the server.');
});
</script>
</body>
</html>
Server
var http = require("http");
var Primus = require("primus");
var server;
var primus;
var options = {
transformer: "engine.io"
};
.............
self.app.post('/api/sendmessage', function(req, res){
var msg = req.body.data;
res.setHeader('Content-Type', 'text/plain');
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
var count = 0;
var interval = setInterval(function(mess) {
if (count < 4) {
var mess = msg + count;
count ++;
console.log(mess);
primus.on("connection", function(spark) {
spark.on("data", function(data) {
spark.write(mess);
});
});
} else {
console.log("Done");
clearInterval(interval);
}
}, 6000, msg);
});
............
self.initializeServer = function() {
self.createRoutes();
self.app = express();
server = http.createServer(self.app)
primus = new Primus(server, options)
.............
I use Nodejs and ExpressJS to create server. Anyone can tel me how to get it work? Thanks
You need to more your
primus.on('connection')
out of theself.app.post
route. As now you're adding connection listeners for EVERY connection you receive. What you are looking for is the broadcasting functionality of Primus. See https://github.com/primus/primus#broadcasting for the correct API for that.