使用 socket.emit 您可以像这样注册自定义事件:
服务器:
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
客户:
var socket = io.connect('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
Socket.send 做同样的事情,但你没有注册到“新闻”,而是注册到消息:
服务器:
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
socket.send('hi');
});
客户:
var socket = io.connect('http://localhost');
socket.on('message', function (message) {
console.log(message);
});