这是我帮助您弄湿脚的最佳方法...
首先是第一件事..必须设置您的服务器端文件...
var http = require('http');
var app = http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end();
});
var io = require('socket.io').listen(app);
io.set('log level', 1); // keep logging to only the essentials
io.set('transports', ['websocket']); // this will only allow clients that support web sockets
io.sockets.on('connection', function(socket) { // when a socket connects and publishes a "connection" message Think of this like pub/sub here.. The connection event happens any time a client connects.
socket.on('GetSession', function(){
socket.emit('SessionID', {
SessionID : socket.id //socket.id = the socket ID that is auto generated. So what we are doing here is when a client connects we will send back to them their session ID. I use this as a simple way to verify that the connection is successful on the client side.
});
socket.on('SendMessage', function(msg){ // So here is an example of that pub/sub I am talking about. We are going to publish to anything listening on "CreateRoom" a message.
socket.emit('Message', msg); // Here we take anyone listening on the message channel and send them whatever was emitted.
});
});
app.listen(3000);
接下来让我们看看客户...
var socket = io.connect('http://localhost:3000');
function GetInfo(){
socket.emit('GetSession', ''); // The client is now initiating the request we setup earlier to get its socket.id from the server.
}
socket.on('SessionID', function(msg) {
socket.emit('SendMessage', msg + ' Has Connected'); // When the server returns the socket.id the client will emit a message to the server for anyone else who is subscribed to the "message" channel. My terminology for these explanations is not accurate but I think that this way of stating things is a lot easier to wrap your head around...
});
socket.on('message', function(msg) {
console.log(msg); // here the client is listening on the "message" channel. Whenever the server sends a message to this channel the client will write the data to the console.
});
希望这可以帮助你看到。如果您将 socket.io 视为一个发布/订阅应用程序,我认为它很容易上手(起初,因为有更多功能)。