我有一个运行服务器与Apache和Socket.IO。我试图在我的网站上使用socket.io发送和接收消息。Socket.IO Websocket发送消息不适用于Firefox和Chrome
这是我的服务器代码:
var fs = require('fs');
var hskey = fs.readFileSync('file.key');
var hscert = fs.readFileSync('file.crt');
var options = {
key: hskey,
cert: hscert
};
var app = require('https').createServer(options);
var io = require('/usr/local/lib/node_modules/socket.io').listen(app);
app.listen(8181);
io.sockets.on('connection', function (socket) {
socket.emit('serverMessage', 'Bienvenue master!');
socket.broadcast.emit('serverMessage', 'New user online');
});
这是网页:
<!doctype html>
<html>
<head>
<title>Socket.io Test</title>
<script src="./socket.io.js"></script>
</head>
<body>
<script>
var socket;
var firstconnect = true;
function connect() {
if(firstconnect) {
socket = io.connect('https://secure.mysite.com:8181');
socket.on('serverMessage', function(data){ message(data); });
socket.on('connect', function(){ status_update("Connected to Server"); });
socket.on('disconnect', function(){ status_update("Disconnected from Server"); });
socket.on('reconnect', function(){ status_update("Reconnected to Server"); });
socket.on('reconnecting', function(nextRetry){ status_update("Reconnecting in "
+ nextRetry + " seconds"); });
socket.on('reconnect_failed', function(){ message("Reconnect Failed"); });
firstconnect = false;
}
else {
socket.socket.reconnect();
}
}
function disconnect() {
socket.disconnect();
}
function message(data) {
document.getElementById('message').innerHTML += "<br>" + "Server says: " + data;
}
function status_update(txt){
document.getElementById('status').innerHTML = txt;
}
function esc(msg){
return msg.replace(/</g, '<').replace(/>/g, '>');
}
function send() {
socket.send('clientMessage', 'world');
};
</script>
<h1>Socket.io Test</h1>
<div><p id="status">Waiting for input</p></div>
<div><p id="message"></p></div>
<button id="connect" onClick='connect()'/>Connect</button>
<button id="disconnect" onClick='disconnect()'>Disconnect</button>
<button id="send" onClick='send()'/>Send Message</button>
</body>
</html>
一切似乎Safari浏览器(网页套接字)和Opera(JSON池)下工作正常,但与Firefox和Chrome(websocket)我无法从客户端向服务器发送任何消息。其他一切正在工作,我可以握手,连接并获取服务器消息。我做了大量的研究,但似乎我是唯一有这个问题的人。
感谢您的帮助!
看看这里的websockets的“浏览器兼容性”吗? https://developer.mozilla.org/en/WebSockets – 2012-04-07 06:30:40
Chrome可能也有不同于标准webkit的websockets实现 - 真的不确定这一点。 – 2012-04-07 06:32:37
我使用socket.io作为websocket,因为它也支持flashsocket和长池,所以它应该可以工作,但发送消息不可以 – exomic 2012-04-09 02:26:54