js无法将消息发送到在线特定套接字

js无法将消息发送到在线特定套接字

本文介绍了Node.js无法将消息发送到在线特定套接字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试基于socket.io实现简单的推送通知,在我的简单代码中练习如何执行我编写的简单代码,在我的代码中我无法向连接的用户发送消息,使用登录时进入系统,我用redis上的密钥存储socket.io,但是在向用户发送消息时,我从redis获取了作为用户名的密钥,并从redis存储了socket.io值,而我试图发送,我得到了相同的值,但消息不会发送给用户

i'm trying to implement simple push notification based on socket.io, in my simple code to practice how can i do that i wrote simple code, in my code i can't send message to connected user , when use logged into system i store socket.io with the key on redis, but on send message to user i get key as username from redis and stored socket.io value from redis and i'm trying to send, i get the same socket.io value but message dont send to user

客户端:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>
        Document
    </title>
    </meta>
    <script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#login').click(function () {
                socket.emit('login', {username: 'a', password: 'a'});
            });

            $('#mesage').click(function () {
                socket.emit('message', 'a');
            });
        });
    </script>
    <script>
        var socket = new io.connect('http://192.168.1.35:3000', {
            port      : 3000,
            transports: ['websocket']
        });

        socket.on('connect', function () {
            console.log('connected!');
        });

        socket.on('login', function (message) {
            console.log(message);
        });

        socket.on('message', function (message) {
            console.log(message);
        });

        socket.on('hello,', function (message) {
            console.log(message);
        });

        socket.on('success', function (data) {
            console.log(data);
        });

    </script>
</head>
<body>
<h3 id="login">
    login
</h3>

<h3 id="mesage">
    mesage
</h3>
</body>
</html>

服务器端:

var socket      = require('socket.io'),
    express     = require('express'),
    app         = express(),
    server      = require('http').createServer(app),
    io          = socket.listen(server),
    port        = process.env.PORT || 3000,
    redis       = require("redis"),
    redisClient = redis.createClient();

socket.on('connection', function (socket) {
    socket.on('login', function (data) {
        login(data.username, data.password, function (success, value) {
            if (success) {
                redisClient.exists(data.username, function (err, doesExist) {
                    if (err) return;
                    if (!doesExist) {
                        redisClient.set(data.username, socket.id);
                    }
                    else {
                        redisClient.del(data.username);
                        redisClient.set(data.username, socket.id);
                    }
                    log.info("SOCKET ID: " + socket.id);
                });
                socket.emit('login', {result: success, id: socket.id});
            } else {
                socket.emit('login', {result: false, id: socket.id});
            }
        });
    });
    socket.on('message', function (username) {
        redisClient.get(username, function (err, socketId) {
            if (err)
                socket.emit('message', err);
            io.to(socketid).emit('message', 'for your eyes only');
        });
    });

});

当我单击login时,我得到以下结果:

when i click on login i get this result:

 Object { result=true,  id="/#A5sR-Xo-Owo97NvRAAAB"}

当我单击消息时,我得到以下结果:

and when i click on message i get this result:

user not connected /#A5sR-Xo-Owo97NvRAAAB

socket.id都相同,但是客户端没有收到任何消息,服务器以user not connected

both of socket.ids are the same, but client dont get any message and server return this message as user not connected

推荐答案

此代码中似乎有错字:

redisClient.get(username, function (err, socketId) {
    if (err)
        socket.emit('message', err);
    io.to(socketid).emit('message', 'for your eyes only');
});

您的回调函数将socketId作为第二个参数,但是您在发送消息时使用socketid(小写).

Your callback receives socketId as the second argument, but you use socketid (lowercase) when you send a message.

另外,发送错误消息时最好退出函数:

Also it's better to quit a function when you send an error message:

if (err) return socket.emit('message', err);

或:

if (err) {
    socket.emit('message', err);
    return;
}

否则,您可能会遇到意外错误.

otherwise you might have unexpected errors.

希望这会有所帮助.

这篇关于Node.js无法将消息发送到在线特定套接字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 19:03