QT QLocalServer服务端与node IPC通信

Posted caiyingyong

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了QT QLocalServer服务端与node IPC通信相关的知识,希望对你有一定的参考价值。

QT 服务端代码:

.h

#ifndef LOCALSERVER_H
#define LOCALSERVER_H

#include <QObject>
#include <QtNetwork>

class LocalServer : public QObject
{
    Q_OBJECT
public:
    explicit LocalServer(QObject *parent = nullptr);
    ~LocalServer();

    bool RunServer(QString name);

signals:

public slots:
    void serverNewConnectionHandler();
    void socketReadyReadHandler();

private:
    QLocalServer *m_localServer;
    QLocalSocket *m_socket;
};

#endif // LOCALSERVER_H

.cpp

#include "localserver.h"

#include <QDebug>

LocalServer::LocalServer(QObject *parent) :
    QObject(parent), m_localServer(nullptr), m_socket(nullptr)
{
    m_localServer = new QLocalServer();
    connect(m_localServer, &QLocalServer::newConnection, this, &LocalServer::serverNewConnectionHandler);
}

LocalServer::~LocalServer() {
    m_localServer->close();
    delete m_localServer;
}

bool LocalServer::RunServer(QString name) {
    QLocalServer::removeServer(name);
    return m_localServer->listen(name);
}

void LocalServer::serverNewConnectionHandler() {
    qDebug() << "new connction";
    m_socket = m_localServer->nextPendingConnection();
    connect(m_socket, &QLocalSocket::readyRead, this, &LocalServer::socketReadyReadHandler);
    connect(m_socket, &QLocalSocket::disconnected, m_socket, &QLocalSocket::deleteLater);
    connect(m_socket, &QLocalSocket::disconnected, [=]() {
        qDebug() << "disconnected";
    });
}

void LocalServer::socketReadyReadHandler() {
    QTextStream stream(m_socket);
    qDebug() << "DATA:" << stream.readAll();
}

 

nodejs 服务端代码:

let net = require(‘net‘);
let path = require(‘path‘);

let server = net.createServer(function (connect) {
    connect.on(‘error‘,function(err){
        console.log(‘socket error:‘ + err);
        connect.end();
    });
    connect.on(‘close‘,function(data){
        console.log(‘client closed:‘, data);
    });
    connect.on("data",function (data) {
        console.log(‘data:‘, data);
    })
}).listen(path.join(‘\\?\pipe‘,‘\tmp\echo.sock‘));

server.on("error",function(err){
    console.log("error:" + err);
});

 

nodejs 客户端代码:

let net = require(‘net‘);
let path = require(‘path‘);

let client = new net.Socket();

let strPath = path.join(‘\\?\pipe‘, ‘/tmp/echo.sock‘);
console.log(strPath);
client.connect(strPath, () => {
  console.log("已连接到服务器"); 
})

client.on(‘data‘, (data) => {
    console.log(‘data:‘, data.toString());
})

client.on(‘close‘, () => {
    console.log(‘Connection closed‘);
})

client.on(‘end‘, () => {
    console.log(‘已从服务器断开‘);
})

client.on(‘error‘, (err) => {
    console.log("err:", err);
})

 

以上是关于QT QLocalServer服务端与node IPC通信的主要内容,如果未能解决你的问题,请参考以下文章

Qt之进程间通信(本地套接字)

QLocalServer 不会启动传入连接

Qt基础之二十:进程间通信

Qt基础之二十:进程间通信

node.js中net网络模块TCP服务端与客户端的使用

在 QtService 上使用 QLocalServer:如何为 QLocalServer 创建的命名管道设置安全属性?