我有一個運行服務器與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