使用socket.io和node.js从服务器向客户端发送消息

Send message to client from server using socket.io and node.js

本文关键字:客户端 消息 服务器 io socket node js 使用      更新时间:2023-09-26

我使用的是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:对象不是函数在Socket。

我想我明白你想做什么了。你想通过使用消息的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"] });
    });
});

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

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"] });
    });
});