【发布时间】:2018-01-10 20:37:48
【问题描述】:
我正在使用带有 socket.io 的 react-native 来发送和接收联系请求,但我的代码只发送给发射器,而没有发送给其他人。
这是服务器端:
users = []; // Each time a new user joins the server they are saved in this array
socket.on('create connection', function(data, callback) {
if(data.receiverId in users) { // If the user you want to add is online then callback is true else callback is false
// The underneath line is the one that I will be using but nothing happend
//io.sockets.in(data.receiverId).emit('save room', data);
// So I created this one to see if I actually was emitting something
socket.emit('save room', data); // I found out that the emitting was working but only with the emitter
callback(true);
}else
callback(false);
});
所以我的结论是我的服务器端是正确的,问题出在我的客户端
这是我的客户端:
constructor() {
this.socket = SocketIOClient('http://192.168.15.4:8000');
this.socket.on('save room', function (data) { // This is where the server calls the emit. It was at first inside the connect function but I moved it to the constructor to see if that way all clients could get it, results are the same
Alert.alert(
'Accept Connection?',
'User: '+data.emitterId+' sent you a connection request',
[
{
text: 'Accept',
onPress: () => {},
},
{
text: 'Refuse',
onPress: () => {},
},
],
{cancellable: false}
);
})
}
@action connect(data, callback1) { // this access the function we had previously in the server
this.socket.emit('create connection', data, function (callback2) {
if(!callback2)
Alert.alert(
'User Offline',
'This user is currently offline try again later',
[
{
text: 'OK',
onPress: () => {callback1(false)},
},
],
{cancellable: false}
);
else {
callback1(true)
}
});
}
我认为问题在于我放置 this.socket.on('save room') 函数的位置,但在 react-native 我真的不知道放在哪里。
【问题讨论】:
-
您可以尝试分享以下结果吗? 1) 将
this.socket.on移动到componentDidMount();2) 而不是socket.emit,尝试socket.broadcast.emit -
如果我做第一,甚至发射器都没有收到警报,但第二个它可以工作!但是如果我这样使用它,所有在线用户都会收到警报。我怎么能像这样“io.sockets.in(data.receiverId).emit('save room', data);”?
-
socket.broadcast.emit将您的消息发送给除发件人之外的所有人。所以问题应该是你没有被识别为发件人。你能尝试在this.socket.on之前的构造函数中添加this.socket.open()吗? -
是的,很抱歉,它会将消息发送给除发件人以外的所有人
标签: javascript react-native socket.io