Connecting to an already established UNIX socket with node.js?

放肆的年华 提交于 2019-11-30 03:50:06

问题


I am working on a node.js application that will connect to a UNIX socket (on a Linux machine) and facilitate communication between a web page and that socket. So far, I have been able to create socket and communicate back and forth with this code in my main app.js:

var net = require('net');
var fs = require('fs');
var socketPath = '/tmp/mysocket';

fs.stat(socketPath, function(err) {
    if (!err) fs.unlinkSync(socketPath);
    var unixServer = net.createServer(function(localSerialConnection) {
        localSerialConnection.on('data', function(data) {
            // data is a buffer from the socket
        });
        // write to socket with localSerialConnection.write()
    });

unixServer.listen(socketPath);
});

This code causes node.js to create a UNIX socket at /tmp/mysocket and I am getting good communication by testing with nc -U /tmp/mysocket on the command line. However...

I want to establish a connection to an already existing UNIX socket from my node.js application. With my current code, if I create a socket from the command line (nc -Ul /tmp/mysocket), then run my node.js application, there is no communication between the socket and my application (The 'connect' event is not fired from node.js server object).

Any tips on how to go about accomplishing this? My experiments with node.js function net.createSocket instead of net.createServer have so far failed and I'm not sure if that's even the right track.


回答1:


The method you're looking for is net.createConnection(path):

var client = net.createConnection("/tmp/mysocket");

client.on("connect", function() {
    ... do something when you connect ...
});

client.on("data", function(data) {
    ... do stuff with the data ...
});



回答2:


You can also connect to a socket like this:

http://unix:/path/to/my.sock:



来源:https://stackoverflow.com/questions/20807900/connecting-to-an-already-established-unix-socket-with-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!