socket.emit只发射到发射器

时间:2018-01-10 20:37:49

标签: javascript react-native socket.io

我正在使用react-native和socket.io发送和接收联系请求,但我的代码只发送到发射器而不是其他人。

这是服务器端:

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('保存房间') 功能的地方,但是反应原生我真的不知道把它放在哪里。

1 个答案:

答案 0 :(得分:0)

感谢 @H。 Tugkan kibar @azium 我意识到问题出在我的服务器端,发送给特定用户的正确方法是这样的:

socket.broadcast.to().emit();