简体   繁体   English

Node.js WebSocket服务器和TCP服务器连接

[英]Node.js websocket-server and tcp-server connection

Related to this question Browser with JavaScript TCP Client I asked whether I can connect from a browser to a tcp server. 与此问题相关的问题使用JavaScript TCP Client的浏览器,我询问是否可以从浏览器连接到TCP服务器。 I found out that it won't work so I asked for another solution. 我发现这行不通,所以我要求其他解决方案。 '0101' provided me to built up two servers. “ 0101”让我建立了两个服务器。 One tcp server for a c++ application that connects to and one websockets server that receives data from the browser. 一个用于连接到c ++应用程序的tcp服务器,一个用于从浏览器接收数据的websockets服务器。 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. 我最初建立了它们中的每一个,但是我不知道如何连接它们,因此我可以从c ++应用程序中的浏览器接收数据。

Here is the websockets-server: 这是websockets服务器:

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: 这是tcp服务器:

// 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 两者都被复制到互联网之外以测试某些情况

Drop the TCP server and make the C++ client connect to the websockets server instead. 删除TCP服务器,并使C ++客户端连接到websockets服务器。 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). 您需要在C ++端的TCP连接的顶部实现websockets协议(您真正需要的只是一些前言以协商websocket)。 You have problems here with both servers trying to use port 80. 这两个服务器都尝试使用端口80时遇到问题。

By the way, you should also consider using HTTPS for the websocket instead of HTTP since it avoids problems with proxy traversal. 顺便说一句,您还应该考虑对Websocket使用HTTPS而不是HTTP,因为它避免了代理遍历的问题。 But get the HTTP case working first as this will be more complicated to implement on the C++ end. 但是首先使HTTP情况起作用,因为在C ++端实现起来会更加复杂。

Create a TCP server (NodeJS example) 创建一个TCP服务器(NodeJS示例)

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 然后在同一个文件中(当然是可选的)创建一个具有不同端口号的WS服务器

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. 现在您应该有两台服务器,一台用于常规套接字,另一台用于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... //正如我在前面的问题和Pete中提到的那样,最好也使用C ++中的WebSocket而不是创建两个服务器...

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

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