简体   繁体   中英

How to combine express with tcp-socket in Node.js

I implemented my first web-app with node.js and express. It works fine. The structure is as followed.

app.get('/', (request, response) => {
    response.render('home', {orders, actualPosition, path});
});

app.post('/', function(req, res){
   //do something
    res.redirect('/')
})

app.listen(8080, () => {
    console.log(`Listening on http://127.0.0.1:${port}/ !`);
})

Now I would like to communicate with a matlab-program, preferable via tcp/ip. Means I have got a matlab-program, that exchanges data with the web-application. I achieved to send data by opening a server with net on another port like that:

var server = net.createServer(function(socket) {
    //read data
    socket.setEncoding("ascii"); //set data encoding (either 'ascii', 'utf8', or 'base64')
    socket.on('data', function(data, res) {
       //update new data in browser
    });

    //send data
    socket.write('Echo server\n');
    socket.pipe(socket);
});

server.listen(8081, '127.0.0.1');

My problem now is how can I display received data via tcp/ip in the browser. Can I call app.get('/') somehow from extern to refresh the page. What are my options to get this work?

Thanks already

I think your structure should be close to following:

  • express app accepts request from browser
  • route handler sends request via net server
  • net server responds with data
  • express route handler responds to client with data

So, your mistake is that you'll have http server and net client(not net server). Sample net client.

The solution I realized is to integrate additionally a websocket between Web-Client and Web-Server. The Problem about http is, that you can't do a request from server to client. The server can just react on requests from the client. That's why a websocket is necessary. It allows to send messages/data from the server to the client. The received data can then be displayed by the client.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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