使用node.js连接到已经建立的UNIX套接字? [英] Connecting to an already established UNIX socket with node.js?

查看:119
本文介绍了使用node.js连接到已经建立的UNIX套接字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个node.js应用程序,它将连接到UNIX套接字(在Linux机器上),并促进网页和该套接字之间的通信。到目前为止,我已经能够在我的主app.js中创建套接字并与此代码来回通信:

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);
});

此代码导致node.js在 / tmp /创建UNIX套接字mysocket 我通过在命令行上使用 nc -U / tmp / mysocket 进行测试来获得良好的通信。但是......

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...

我想从我的node.js应用程序建立与现有UNIX套接字的连接。使用我当前的代码,如果我从命令行创建套接字( nc -Ul / tmp / mysocket ),然后运行我的node.js应用程序,之间没有通信套接字和我的应用程序('connect'事件不是从node.js服务器对象触发的。)

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).

有关如何完成此任务的任何提示?我使用node.js函数 net.createSocket 而不是 net.createServer 的实验到目前为止失败了,我不是确定这是否是正确的轨道。

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.

推荐答案

您正在寻找的方法是 net.createConnection(path)

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 ...
});

这篇关于使用node.js连接到已经建立的UNIX套接字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆