我有一个运行着 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) 下,我无法将任何消息从客户端发送到服务器。其他一切正常,我可以握手、连接并获取服务器消息。我做了很多研究,但似乎我是唯一一个遇到这个问题的人。
谢谢你帮助我!