Node.js与C++的集成

Integration between Node.js and C++

本文关键字:集成 C++ js Node      更新时间:2023-10-16

我有一个Node.js应用程序,我希望它能够将JSON对象发送到C++应用程序中。

C++应用程序将使用Poco库(pocoproject.org)

我希望交互快速,所以最好没有文件或网络套接字。我一直在研究这些领域:

  • 管道
  • 共享内存
  • unixSockets

我应该关注什么,有人能把我的方向指向文档吗。和样品?

首先,需要更多的数据来提供好的建议。

一般来说,共享内存是最快的,因为不需要传输,但它也是最难保持的。不过,我不确定使用Node是否能够做到这一点。

如果这个程序只是为这一个任务运行并关闭,那么将JSON作为启动参数发送到CPP程序可能是值得的

myCPPProgram.exe "JsonDataHere"

性能良好的最简单的事情应该是使用具有一些低开销数据帧格式的Unix域套接字的套接字连接。例如,两个字节的长度后面跟着UTF-8编码的JSON。在C++方面,这应该很容易使用Poco::Net::TCPServer框架来实现。根据您的应用程序将来的发展方向,您可能会遇到这种格式的限制,但如果它基本上只是流式传输JSON对象,那应该没问题。

更简单的是,您可以使用WebSocket,它将为您处理帧,而代价是初始连接设置(HTTP升级请求)的开销。甚至可以在Unix域套接字上运行WebSocket协议。

然而,考虑到JavaScript/node.js的所有开销,(仅本地主机)TCP套接字和Unix域套接字之间的性能差异甚至可能并不显著。此外,如果性能真的是一个问题,那么JSON可能甚至不是正确的序列化格式。

无论如何,如果没有更详细的信息(JSON数据的大小、消息频率),很难给出明确的建议。

我创建了一个TCPServer,它似乎可以工作。然而,如果我关闭服务器并再次启动它,我会收到以下错误:

网络异常:地址已在使用中:/tmp/app.SocketTest

如果套接字存在,是否无法重新连接到套接字?

以下是TCPServer的代码:

#include "Poco/Util/ServerApplication.h"
#include "Poco/Net/TCPServer.h"
#include "Poco/Net/TCPServerConnection.h"
#include "Poco/Net/TCPServerConnectionFactory.h"
#include "Poco/Util/Option.h"
#include "Poco/Util/OptionSet.h"
#include "Poco/Util/HelpFormatter.h"
#include "Poco/Net/StreamSocket.h"
#include "Poco/Net/ServerSocket.h"
#include "Poco/Net/SocketAddress.h"
#include "Poco/File.h"
#include <fstream>
#include <iostream>
using Poco::Net::ServerSocket;
using Poco::Net::StreamSocket;
using Poco::Net::TCPServer;
using Poco::Net::TCPServerConnection;
using Poco::Net::TCPServerConnectionFactory;
using Poco::Net::SocketAddress;
using Poco::Util::ServerApplication;
using Poco::Util::Option;
using Poco::Util::OptionSet;
using Poco::Util::HelpFormatter;

class UnixSocketServerConnection: public TCPServerConnection
/// This class handles all client connections.
{
public:
UnixSocketServerConnection(const StreamSocket& s): 
TCPServerConnection(s)
{
}
void run()
{
try
{
/*char buffer[1024];
int n = 1;
while (n > 0)
{
n = socket().receiveBytes(buffer, sizeof(buffer));
EchoBack(buffer);
}*/
std::string message;
char buffer[1024];
int n = 1;
while (n > 0)
{
n = socket().receiveBytes(buffer, sizeof(buffer));
buffer[n] = '';
message += buffer;
if(sizeof(buffer) > n && message != "")
{
EchoBack(message);
message = "";
}
}
}
catch (Poco::Exception& exc)
{
std::cerr << "Error: " << exc.displayText() << std::endl;
}
std::cout << "Disconnected." << std::endl;
}
private:
inline void EchoBack(std::string message)
{
std::cout << "Message: " << message << std::endl;
socket().sendBytes(message.data(), message.length());
}
};
class UnixSocketServerConnectionFactory: public TCPServerConnectionFactory
/// A factory
{
public:
UnixSocketServerConnectionFactory()
{
}
TCPServerConnection* createConnection(const StreamSocket& socket)
{
std::cout << "Got new connection." << std::endl;
return new UnixSocketServerConnection(socket);
}
private:
};
class UnixSocketServer: public Poco::Util::ServerApplication
/// The main application class.
{
public:
UnixSocketServer(): _helpRequested(false)
{
}
~UnixSocketServer()
{
}
protected:
void initialize(Application& self)
{
loadConfiguration(); // load default configuration files, if present
ServerApplication::initialize(self);
}
void uninitialize()
{
ServerApplication::uninitialize();
}
void defineOptions(OptionSet& options)
{
ServerApplication::defineOptions(options);
options.addOption(
Option("help", "h", "display help information on command line arguments")
.required(false)
.repeatable(false));
}
void handleOption(const std::string& name, const std::string& value)
{
ServerApplication::handleOption(name, value);
if (name == "help")
_helpRequested = true;
}
void displayHelp()
{
HelpFormatter helpFormatter(options());
helpFormatter.setCommand(commandName());
helpFormatter.setUsage("OPTIONS");
helpFormatter.setHeader("A server application to test unix domain sockets.");
helpFormatter.format(std::cout);
}
int main(const std::vector<std::string>& args)
{
if (_helpRequested)
{
displayHelp();
}
else
{
// set-up unix domain socket
Poco::File socketFile("/tmp/app.SocketTest");
SocketAddress unixSocket(SocketAddress::UNIX_LOCAL, socketFile.path());
// set-up a server socket
ServerSocket svs(unixSocket);
// set-up a TCPServer instance
TCPServer srv(new UnixSocketServerConnectionFactory, svs);
// start the TCPServer
srv.start();
// wait for CTRL-C or kill
waitForTerminationRequest();
// Stop the TCPServer
srv.stop();
}
return Application::EXIT_OK;
}
private:
bool _helpRequested;
};
int main(int argc, char **argv) {
UnixSocketServer app;
return app.run(argc, argv);
}

我想要的解决方案是使用unix域套接字。该解决方案将在Raspbian设置上运行,套接字文件位于/dev/shm中,该文件安装到RAM中。

在C++方面,我使用Poco::Net::TCPServer框架,如本文其他部分所述。

在Node.js端,我使用nodeipc模块(http://riaevangelist.github.io/node-ipc/)。