Node.js websocket-server and tcp-server connection

2020-06-28 16:20发布

问题:

Related to this question Browser with JavaScript TCP Client I asked whether I can connect from a browser to a tcp server. I found out that it won't work so I asked for another solution. '0101' provided me to built up two servers. One tcp server for a c++ application that connects to and one websockets server that receives data from the browser. I have originally built up each one of them, but I don't know how to connect them so I can receive data from the browser in the c++ application.

Here is the websockets-server:

var ClientListe = {};
// Anzahl der Verbundenen Clients
var ClientAnzahl=0;

// Websocket-Server
var WebSocketServer = require('ws').Server
var wss = new WebSocketServer({host: '127.0.0.1',port: 80});

wss.on('connection', function(ws) 
{
    // Client-Anzahl hochzählen
    ClientAnzahl++;
    // Client-Verbindung mit in die Client-Liste Aufnehmen
    ws['AUTH'] = ClientAnzahl;
    ClientListe[ws['AUTH']] = ws;
    // Ausgabe
    console.log('client '+ClientAnzahl+' verbunden...');

    ws.on('message', function(message) 
    {
        console.log('von Client empfangen: ' + message);

        for(client in ClientListe)
        {
            ClientListe[client].send('von Server empfangen: ' + message);
        }

    });

    ws.on('close', function() 
    {
        // Client aus der ClientListe Löschen
        delete ClientListe[ws['AUTH']];

        // Nachricht der Trennung an die Console ausgeben
        console.log('Client '+ ws['AUTH'] +' getrennt.');
    });

});

and here is the tcp server:

// Load the TCP Library
net = require('net');

// Keep track of the chat clients
var clients = [];

// Start a TCP Server
net.createServer(function (socket) {

// Identify this client
socket.name = socket.remoteAddress + ":" + socket.remotePort;

// Put this new client in the list
clients.push(socket);

// Send a nice welcome message and announce
socket.write("Welcome " + socket.name + "\n");
broadcast(socket.name + " joined the server\n", socket);

// Handle incoming messages from clients.
socket.on('data', function (data) {
broadcast(socket.name + " message: " + data, socket);
});

// Remove the client from the list when it leaves
socket.on('end', function () {
clients.splice(clients.indexOf(socket), 1);
broadcast(socket.name + " left the server.\n");
});
// Send a message to all clients
function broadcast(message, sender) {
clients.forEach(function (client) {
// Don't want to send it to sender
if (client === sender) return;
client.write(message);
});
// Log it to the server output too
process.stdout.write(message)
}

}).listen(80);

// Put a friendly message on the terminal of the server.
console.log("TCP Server running at localhost port 80\n");

Both are copied out of the internet for testing some cases

回答1:

Create a TCP server (NodeJS example)

var net = require("net");

var server = net.createServer(function(c) { //'connection' listener
    console.log('server connected');

    c.on('end', function() {
        console.log('server disconnected');
    });

    c.write('hello\r\n');
    c.pipe(c);
});

server.listen(8124, function() { //'listening' listener
    console.log('server bound');
});

Then in the same file (optionally of course) create a WS server with different port number

var WebSocketServer = require("ws").Server;

var wss = new WebSocketServer({
    port: 8080
});

wss.on("connection", function(ws) {
    console.log("CONNECTED");

    // ws.on("message"), ws.on("close"), ws.on("error")
});

Now you should have two servers, one for regular sockets and another one for WebSockets.

// As I mentioned in the previous question and Pete as well, it is a lot better to use WebSockets in C++ as well instead of creating two servers...



回答2:

Drop the TCP server and make the C++ client connect to the websockets server instead. You'll need to implement the websockets protocol on top of your TCP connection at the C++ end (all you really need is a bit of pre-amble to negotiate the websocket). You have problems here with both servers trying to use port 80.

By the way, you should also consider using HTTPS for the websocket instead of HTTP since it avoids problems with proxy traversal. But get the HTTP case working first as this will be more complicated to implement on the C++ end.