我不确定如何理解 socket.io 中消息的使用。我正在尝试将消息从客户端发送到服务器,然后服务器回复客户端(基本不?)。
这是服务器代码:
var fs = require('fs');
var hskey = fs.readFileSync('ssl.key');
var hscert = fs.readFileSync('ssl.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', 'Hello world!');
io.sockets.emit('serverMessage', 'A user connected');
io.sockets.on('clientMessage', function (socket) {
socket.emit('serverMessage', 'Gotamessage bitch!');
console.log('I received a message by ', from, ' saying ', msg);
});
socket.on('disconnect', function () {
io.sockets.emit('serverMessage', 'A user disconnected');
});
});
这是客户端代码:
<script>
var socket;
var firstconnect = true;
function connect() {
if(firstconnect) {
socket = io.connect('https://secure.connectednodes.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.emit('clientMessage', 'Yo server');
};
</script>
我设法让连接和断开连接工作,但我无法让 io.sockets.on('clientMessage' 工作。有什么想法吗?