繁体   English   中英

Node.js HTTP和TCP客户端连接

[英]Node.js HTTP and TCP Clients Connection

我正在尝试创建一个系统,其中有一个在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天! TIA!

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

如果知道您使用的桌面客户端的类型,我将尝试提供更多帮助。

您需要对http客户端使用http或express。 例如 :

var express = require('express')
, app = express()
, http = require('http')
, server = http.createServer(app)
, io = require('socket.io').listen(server);

server.listen(8080);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM