我的服务器端代码如下:
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
app.listen(1000);
function handler (req, res) {
function (err, data) {
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
socket.emit('message', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
我的浏览器端代码如下:
window.WebSocket = window.WebSocket || window.MozWebSocket;
if (!window.WebSocket){
alert("WebSocket not supported by this browser");
return;
}
var websocket = new WebSocket("ws://127.0.0.1:1000/");
websocket.onmessage = function(evt){
var data = evt.data;
console.log(data);
}
首先我用'node server.js'运行服务器,没关系。当我运行cient代码时,浏览器说它无法连接到'
',为什么?客户端也必须用socket.io写吗?http://127.0.0.1:1000