开发者

node.js - communicate with TCP server (data == JSON)

开发者 https://www.devze.com 2023-02-23 07:55 出处:网络
I\'m new to node.js, dived into it during the last weekend and had fun with various examples and small tutorials.

I'm new to node.js, dived into it during the last weekend and had fun with various examples and small tutorials. Now I'd like to start a little project for my local area network and have a few questions to get myself into the right direction.

Setup:

I've got a server service running on my lan. It's possible to communicate with that service via TCP and/or HTTP (it's possible to enable or disable TCP or HTTP or both of them) on a specific port and sends and re开发者_Go百科ceives data via JSON on a request. What I basically want to do is to create a webinterface based on node.js for that service, to receive and send JSON data with a webbrowser from and to that service.

Problem:

I already do know how to setup an http server based on node.js. But right now I'm stuck in finding an idea how to create a client based on node.js which stands between the service and the webbrowser client to pass through data from client to server and vise versa. Something like a router or proxy.

Here is a basic scheme based on the client's (webbrowser) point of view:

Send: Webbrowser requests -> node.js routes -> service receives

Receive: Webbrowser receives <- node.js routes <- service responds

Questions:

- Go for TCP or HTTP? (maybe disabling the HTTP Server would spare some ressources) - maybe already answered by this post

- Are there any node.js packages that would fit my needs?

- Go for a framework (expressions?) or would plain node.js be just enough?

- Any hints appreciated :)

edit:

- Is it possible to bind a network device like eth0 inside node.js instead of defining the ip address?

Thanks for your help && best regards

cefra


There's no reason why you can't have a REST HTTP service.

Use something like express to handle routing.

If I understand your problem correctly then you have a webservice written in "foobar" on a TCP port somewhere you can connect to with node.

So if your using express you would write something like

app.get("/resources/", function(req, res) {
    var socket = new net.Socket();
    socket.connect(port, host, function() {
        socket.on("data", function(json) {
            res.contentType("json");
            res.send(json);
            socket.end();
        });
        socket.write(...);
    });
});

So basically you've written a http middleman that contacts your service over TCP then writes the data down the response of your HTTP request.

0

精彩评论

暂无评论...
验证码 换一张
取 消