Ins*_*dJW 12 node.js socket.io
我有两个单独的文件,一个是服务器端JS.
另一个是动态生成的客户端PHP.
这两个文件成功地通过Socket.IO相互通信.
我知道我可以通过使用.of()来限制命名空间但不能使用
处理动态创建的聊天室.
所以我决定同时使用它们
.of('/chat')
Run Code Online (Sandbox Code Playgroud)
和房间功能
.join('room name')
Run Code Online (Sandbox Code Playgroud)
我可以找到服务器端示例,但无法找到客户端示例.
下面是Socket.IO github中唯一给出的服务器端代码片段
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
socket.join('justin bieber fans');
socket.broadcast.to('justin bieber fans').emit('new fan');
io.sockets.in('rammstein fans').emit('new non-fan');
});
Run Code Online (Sandbox Code Playgroud)
socket.broadcast.to('justin bieber fans').emit('new fan');
io.sockets.in('rammstein fans').emit('new non-fan');
Run Code Online (Sandbox Code Playgroud)
这两者有什么区别?
socket.to('room name').emit('event')
Run Code Online (Sandbox Code Playgroud)
代替
io.sockets.in('room name').emit('new non-fan');
Run Code Online (Sandbox Code Playgroud)
.send()
Run Code Online (Sandbox Code Playgroud)
代替
.emit()
Run Code Online (Sandbox Code Playgroud)
有点.send()对我不起作用,我想知道这两者之间的区别.
谢谢,我为有关Socket.IO的多个问题道歉.
Gok*_*ank 10
1) -
i)io.sockets.in().emits():它向x房间的所有人发出/发送自定义事件.防爆;
/* Send message to the room1. It broadcasts the data to all
the socket clients which are connected to the room1 */
io.sockets.in('room1').emit('function', {foo:bar
});
Run Code Online (Sandbox Code Playgroud)
ii)socket.broadcast.to().emit():我向除x房间中的发送者之外的所有人发送/发送自定义事件.防爆;
io.sockets.on('connection', function (socket) {
socket.on('function', function(data){
/* Broadcast to room1 except the sender. In other word,
It broadcast all the socket clients which are connected
to the room1 except the sender */
socket.broadcast.to('room1').emit('function', {foo:bar});
}
}
Run Code Online (Sandbox Code Playgroud)
2) -第一个,您将自定义事件发送/发送到单个客户端(套接字1).第二个,您向x room中的所有客户端发出/发送自定义事件.
3) - emit()和send()之间的区别;
socket.emit():是一个函数,它向一个客户端发送/发送带有数据的自定义事件.socket.emit()至少需要两个参数,第一个是自定义事件名,第二个是依此类推,其中一个是你要传递的数据.防爆;
socket.emit('addUser',{nickname:'John'});
您可能需要使用socket.on()注册并监听此自定义事件.例:
socket.on('addUser',function(data){
console.log(data.nickname); // it will return 'John'
}
Run Code Online (Sandbox Code Playgroud)
socket.send():与socket.emit()几乎相同,这次它使用默认事件名称'message'.所以它只需要一个参数,你想传递的数据.例:
socket.send('hi');
Run Code Online (Sandbox Code Playgroud)
这次你注册并收听'消息'事件名称;
socket.on('message', function (data) {
console.log(data); // it will return 'hi'
})
Run Code Online (Sandbox Code Playgroud)
希望这会有所帮助!
我很久没有使用过Socket.IO了
1.)正如文档所述:"广播意味着向除了启动它的套接字之外的所有人发送消息." 在使用Socket.IO代码进行一些搜索之后,您可以查看/lib/socket.js中的Socket.prototye.packet.
当您第一次打电话时,您将用户设置为"justin bieber粉丝"会议室,并为除插座之外的所有人播放"新粉丝".在第二个例子中,你正在为'rammstein粉丝'中的每个人播放'发送新的非粉丝'.
2.)在第一次通话中,您只为单个用户发出"事件",并向该单个房间发送消息.
在第二个电话中,您正在为该房间中的每个人发送信息.
3.)再看看源代码,它们看起来非常相似,只是socket.io协议接受3种不同类型的消息:"event","json","message".使用.send,您可以发送json字符串或消息.使用.emit,您将向客户端发送一个事件.它没有多大区别,它们几乎在内部处理相同,但您应该使用最适合您需求的那个.
| 归档时间: |
|
| 查看次数: |
10929 次 |
| 最近记录: |