【问题标题】:Send message to client from server using socket.io and node.js使用 socket.io 和 node.js 从服务器向客户端发送消息
【发布时间】:2014-10-06 21:55:17
【问题描述】:

我正在使用 socket.io 和 node.js 。我能够从服务器向所有客户端广播消息,但是在将消息从服​​务器发送到特定客户端时遇到问题。 我是这个 socket.io 和 node.js 的新手

下面是为客户和服务截取的代码

服务器代码:

var http = require('http'),
fs = require('fs');

var express = require('express');

var app = http.createServer(function (request, response) {
fs.readFile("client.html", 'utf-8', function (error, data) {

if(error)
    {
            responce.writeHead(404);
            responce.write("File does not exist");
            responce.end();
    }
    else
    {
            response.writeHead(200, {'Content-Type': 'text/html'});
            response.write(data);
            response.end();
    }
 });
}).listen(1337);


var io = require('socket.io').listen(app);


var clients = [ ] ;
var socketsOfClients = {};

io.sockets.on('connection', function(socket)
{


    socket.on('message_to_server', function(data)
    {


            clients.push(socket.id);

            socket(clients[0]).emit("message_to_client" , { message: data["message"] });

    });
});

~

客户代码:

<!DOCTYPE html>
<html>
<head>
    <script src="/socket.io/socket.io.js"></script>
    <script type="text/javascript">
        // our socket.io code goes here

        var socketio = io.connect("127.0.0.1:1337");

        socketio.on("message_to_client", function(data) {
        document.getElementById("chatlog").innerHTML = ("<hr/>" +
        data['message'] + document.getElementById("chatlog").innerHTML);
        });

        function sendMessage() {
        var msg = document.getElementById("message_input").value;
        socketio.emit("message_to_server", { message : msg});
        }
    </script>
</head>
<body>
    <input type="text" id="message_input"/>
    <button onclick="sendMessage()">send</button>
    <div id="chatlog"></div>
</body>
</html>

~

当我执行时,它会给出如下错误:

socket(clients[0]).emit("message_to_client" , { message: data["message"] });
    ^

TypeError:对象不是函数 在套接字。

【问题讨论】:

    标签: javascript node.js sockets


    【解决方案1】:

    我想我明白你想要做什么。您想通过使用其 ID 将消息寻址到特定套接字。

    根据文档,socket 不是函数 (http://socket.io/docs/server-api/#socket),因此像 socket() 一样调用它会导致代码失败。

    我们不将套接字存储在数组中,而是尝试将它们存储在哈希中:

    var clients = {};
    
    io.sockets.on('connection', function (socket) {
    
        // store a reference to this socket in the hash, using
        // its id as the hash key
        clients[socket.id] = socket;
    
        socket.on('message_to_server', function (data) {
                // look up a client socket by id (this would come from
                // the client, and would need to be communicated to the
                // client in some way, perhaps with a broadcast message
                // sent to every client whenever another client "logged in"
                var destination = clients[data.destinationId];
    
                // if destination is undefined (falsy) it does not
                // exist in the hash
                if (!destination) {
                        return;
                }
    
                // send a message to the destination
                destination.emit("message_to_client" , { message: data["message"] });
        });
    });
    

    如果您想向连接期间创建的同一个套接字发送消息,则不必将对它的引用存储在哈希或数组中,因为您可以在其中访问它关闭:

    io.sockets.on('connection', function (socket) {
    
        socket.on('message_to_server', function (data) {
    
                // we have a reference to socket from the closure above ^
                socket.emit("message_to_client" , { message: data["message"] });
        });
    });
    

    【讨论】:

    • 太棒了。您能否将我的答案标记为解决方案,以便其他人也可以从中受益?谢谢!
    猜你喜欢
    • 1970-01-01
    • 2015-04-25
    • 2013-09-09
    • 2021-10-10
    • 1970-01-01
    • 1970-01-01
    • 2011-06-06
    • 1970-01-01
    • 2012-05-24
    相关资源
    最近更新 更多