【问题标题】:Node.js HTTP and TCP Clients ConnectionNode.js HTTP 和 TCP 客户端连接
【发布时间】:2014-04-30 12:33:54
【问题描述】:

我正在尝试创建一个系统,其中我有一个用 VB 创建的桌面客户端和一个基于浏览器的客户端,它们可以相互发送消息。我正在使用 Node.js 服务器来处理连接和消息。

这是我的 Node.js 服务器的代码:

    net = require('net')

// Supports multiple client chat application

// Keep a pool of sockets ready for everyone
// Avoid dead sockets by responding to the 'end' event
var sockets = [];

// Create a TCP socket listener
var s = net.Server(function (socket) {

    // Add the new client socket connection to the array of
    // sockets
    sockets.push(socket);

    // 'data' is an event that means that a message was just sent by the 
    // client application
    socket.on('data', function (msg_sent) {
        // Loop through all of our sockets and send the data
        for (var i = 0; i < sockets.length; i++) {
            // Don't send the data back to the original sender
            if (sockets[i] == socket) // don't send the message to yourself
                continue;
            // Write the msg sent by chat client
            sockets[i].write(msg_sent);
        }
    });
    // Use splice to get rid of the socket that is ending.
    // The 'end' event means tcp client has disconnected.
    socket.on('end', function () {
        var i = sockets.indexOf(socket);
        sockets.splice(i, 1);
    });


});

s.listen(8000);
console.log('System waiting at http://localhost:8000');

有了这个服务器,我可以成功地在两个桌面客户端之间发送消息。 但是,因为我使用的是 net 而不是 HTTP,所以我无法连接基于浏览器的客户端。

如何让两个客户端都连接?我真的很感激任何帮助/建议/方向。我已经到处搜索了大约 4 天了!蒂亚!

【问题讨论】:

    标签: javascript vb.net node.js sockets http


    【解决方案1】:

    对于基于浏览器的客户端,您可以使用 http 或 express。也可以检查在 http 端口上工作的 socket.io。

    如果知道您正在使用的桌面客户端的类型,我会尽力提供更多帮助。

    【讨论】:

    • 感谢您的建议。我通过创建两个端口解决了这个问题,一个用于 http 连接,第二个用于 tcp 连接。然后在消息事件中,我将消息从 http 端口传递到 TCP 端口
    猜你喜欢
    • 1970-01-01
    • 2014-03-19
    • 2010-11-18
    • 1970-01-01
    • 2023-04-10
    • 2017-04-06
    • 2018-04-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多