【发布时间】:2012-04-20 12:04:43
【问题描述】:
我有一个正在运行的带有 apache 和 Socket.IO 的服务器。我正在尝试在我的网站上使用 socket.io 发送和接收消息。
这是我服务器的代码:
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 (websocket) 和 Opera (json pooling) 下似乎一切正常,但在 Firefox 和 Chrome (websocket) 下,我无法从客户端向服务器发送任何消息。其他一切正常,我可以握手、连接并获取服务器消息。我做了很多研究,但似乎我是唯一一个遇到这个问题的人。
谢谢你帮助我!
【问题讨论】:
-
在这里查看过 websockets 的“浏览器兼容性”? developer.mozilla.org/en/WebSockets
-
Chrome 的 websockets 实现可能与标准 webkit 不同——对此真的不确定。
-
我将 socket.io 用于 websocket,因为它还支持 flashsocket 和长池,所以它应该可以工作,但不能发送消息
-
socket.io 允许您通过配置参数选择使用哪种传输(客户端),因此请尝试使用这些传输以查看哪些可用/正在连接。您使用的是什么版本的 Firefox 和 Chrome? socket.io 网站上的兼容性信息表明它们应该得到很好的支持,即使不是 websockets。
-
你一定有服务器配置问题 我已经使用 Socket.IO 和 Chrome/Firefox/IE 使用 web/flashsockets 有一段时间了;没有问题。