Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
123 views
in Technique[技术] by (71.8m points)

Angular communication with TCP. Is Node.js needed in between?

I have a chat server written in Erlang. Communication between users is via the TCP protocol by sending simple commands. I need to create a web client in Angular. I tried to find a way to communicate with TCP from within Angular, but found no solution. The only option is WebSockets. That's why I came up with something like this, to set up a server in Node.js, which will be a "translator" between Angular and Erlang and will convert requests and responses from WebSockets to TCP and from TCP to WebSockets.

It can be presented like this:

enter image description here

The code of middleware in Node.js:

const Net = require('net');
const WebSocket = require('ws');
const carrier = require('carrier');

const port_ws = 3000;
const port_tcp = 4000;
const host_tcp = '127.0.0.1';

const tcp = new Net.Socket();
const wss = new WebSocket.Server({ port: port_ws });
const my_carrier = carrier.carry(tcp);

var retrying = false;

function start () {
    tcp.connect(port_tcp, host_tcp);
}

function close () {
    if (!retrying) {
        retrying = true;
    }
    setTimeout(start, 1000);
}

wss.on('connection', function connection(ws) {

    ws.on('message', function (message) {
        message = message.replace(/"/g, '');
        tcp.write(message);
    });

    my_carrier.on('line',  function(line) {
        ws.send(JSON.stringify(line));
    });

});

tcp.on('close', function() {
    close();
});

start();

The code above works very well.

However, it has a big disadvantage. If more than 1 user connects to the chat server, the Erlang server throws an error. The point is that the connection comes from Node.js and not from Angular directly, so it throws an error that the user is already connected.

How do I assign a "connection ID" or something else? How can I tell Erlang that the connection that comes from Node.js is different than previous connection?

Maybe there is some way to connect Angular to the TCP protocol and not use Node.js in this case?

question from:https://stackoverflow.com/questions/65863806/angular-communication-with-tcp-is-node-js-needed-in-between

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...