我是 Nodejs 的新手。我正在编写一个使用 Primus 来通信客户端和服务器的程序。但我无法将消息从服务器发送到客户端。这是我的代码。客户:
<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>
服务器
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)
.............
我使用 Nodejs 和 ExpressJS 来创建服务器。任何人都可以告诉我如何让它工作?谢谢