server端
var http = require('http');
var io = require('socket.io');
//创建server
var server = http.createServer();
//端口8080
var io = io.listen(server);
server.listen(8089);
io.on("connection", function (client) {
setInterval(function () {
client.send(os.freemem() / os.totalmem());
}, 500);
});
client端
<!doctype html>
<html>
<head>
<title> 服务器内存使用情况 </title>
<script src="http://cdn.socket.io/stable/socket.io.js"></script>
<style>
#usage {border : 1px dashed green;}
</style>
<script>
var canvas, width = 200, height = 200, buffer = [], max = 200;
function updateChart(data) {
if (buffer.length >= max) {
buffer.unshift();
}
buffer.push(data);
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, width, height);
for (var i = 1, n = buffer.length; i < n; i++) {
ctx.strokeStyle = "red";
ctx.beginPath();
ctx.moveTo(i - 1 , buffer[i - 1] * height);
ctx.lineTo(i, buffer[i] * height);
ctx.closePath();
ctx.stroke();
}
}
function onLoad() {
canvas = document.getElementById("usage");
var socket = new io.Socket('192.168.1.3', {port: 8089});
socket.connect(); // 连接到服务器
socket.on("message", function(obj){ // 接收到消息时的处理方法
updateChart(obj);
});
}
</script>
</head>
<body onload="onLoad();">
<h1> 内存使用情况 </h1>
<canvas id="usage" width="200" height="200"></canvas>
</body>
</html>
然后 这两个东西,都放到了我的服务器上,我的服务器地址是192.188.1.3 是php的服务器。 我首先访问了 192.168.1.3:8080/client.html 进入页面端,之后在后台 node 开启了server端。 结果 页面端报错: XMLHttpRequest cannot load http://192.168.1.3:8089/socket.io/xhr-polling//1348727089478. Origin http://192.168.1.3:8080 is not allowed by Access-Control-Allow-Origin. server端报错 info - unhandled socket.io url warn - unknown transport: “undefined” info - unhandled socket.io url warn - unknown transport: "undefined
查了不少资料,发现要改origin 改了也没有用啊。。
改的socketio配置文件manager.js
if (origin) {
// https://developer.mozilla.org/En/HTTP_Access_Control
headers['Access-Control-Allow-Origin'] = origin;
headers['Access-Control-Allow-Credentials'] = 'true';
} headers[‘Access-Control-Allow-Origin’] = “*”
@jiyinyiyong 加了两句 var io = io.listen(server); io.set("origins", “*”); io.set('transports’, [ 'websocket’, 'flashsocket’, 'htmlfile’, 'xhr-polling’, ‘jsonp-polling’ ]); 还是不行啊囧。。。我听一些人说是 socketio的版本问题,可是我用的cdn啊,这也能有版本问题么