Zan*_*r17 18 node.js socket.io
我还没弄明白如何使用socket.io直接响应发件人
我了解到io.sockets.emit发送给所有客户端,但我不会将信息发送回发件人.
码:
socket.on('login', function (data) {
db.users.find({username: cc.lowerCase(data.username)}, function(err, users) {
if (users.length > 0) {
users.forEach( function(user) {
console.log(user.length);
if (user.password == data.password) {
io.sockets.emit('login', { username: user.username });
} else {
io.sockets.emit('error', { message: "Wrong username or password!" });
}
});
} else {
io.sockets.emit('error', { message: "Wrong username or password!" });
}
});
});
Run Code Online (Sandbox Code Playgroud)
Den*_*ret 41
当您的服务器侦听时,您通常会在"connection"事件中获得一个套接字:
require('socket.io').on('connect', function(socket){
Run Code Online (Sandbox Code Playgroud)
套接字连接2个点:客户端和服务器.当您在此套接字上发出时,您将向此特定客户端发出.
示例:
var io = require('socket.io');
io.on('connect', function(socket){
socket.on('A', function(something){
// we just received a message
// let's respond to *that* client :
socket.emit('B', somethingElse);
});
});
Run Code Online (Sandbox Code Playgroud)
请注意,这是两个不同的电话:
socket.emit :发射到一个插座io.sockets.emit :发射到所有套接字Kar*_*son 24
语法在socketio中令人困惑.此外,每个套接字都会自动连接到他们自己的房间ID socket.id(这是私人聊天在socketio中工作的方式,他们使用房间).
发送给发件人,而不是其他人
socket.emit('hello', msg);
Run Code Online (Sandbox Code Playgroud)
发送给所有人,包括发件人(如果发件人在房间里)在房间"我的房间"
io.to('my room').emit('hello', msg);
Run Code Online (Sandbox Code Playgroud)
在房间"我的房间"发送给发件人以外的所有人(如果发件人在房间里)
socket.broadcast.to('my room').emit('hello', msg);
Run Code Online (Sandbox Code Playgroud)
发送给每个房间的每个人,包括发件人
io.emit('hello', msg); // short version
io.sockets.emit('hello', msg);
Run Code Online (Sandbox Code Playgroud)
仅发送到特定套接字(私人聊天)
socket.broadcast.to(otherSocket.id).emit('hello', msg);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
24116 次 |
| 最近记录: |