qt and python named pipe based interprocess communication example

Posted by joma on Sun, 10 Oct 2021 07:03:41 +0200

qt and python named pipe based interprocess communication example

summary

Named pipes is a simple inter process communication (IPC) mechanism, which is mostly supported by Microsoft Windows (excluding Windows CE). Named pipes can support reliable, one-way or two-way data communication between different processes of the same computer or between different processes of different computers across a network. An important reason why named pipes are recommended as process communication schemes is that they make full use of the built-in security features (ACL S, etc.) of windows.
Using named pipes to design cross computer applications is actually very simple, and there is no need to master the knowledge of underlying network transmission protocols (such as TCP, UDP, IP, IPX) in advance. This is because the named pipeline uses the Microsoft network provider (MSNP) redirector to establish communication between processes through the same network, so that the application does not have to care about the details of the network protocol. (– from Baidu Encyclopedia)

QLocalSocket in Qt is realized through named pipe, so QLocalSocket and QLocalServer can be used to realize named pipe communication at Qt end

Example description

The sample program has been uploaded to CSDN, click localserver.zip Download

Use Qt Creator to open the server-side sample project localserver and run it. The running effect is shown in the figure below

The Test button is disabled, indicating that the client is not connected. The status bar displays the pipe name

Open cmd or powershell in the project directory and run the client Python script:

python  .\localclient.py

At this time, the Test button in the server interface becomes enabled. Click the Test button, and the server will send the message 'Hello, Python.' to the client. After receiving the message from the server, the client will output it to the terminal and return the message "Hello, Qt"

After the server receives the message returned by the client, it will be displayed in the text box. The operation effect is as follows:

Server side programming (Qt)

Project profile

Link network module

QT       += core gui network

mainwindow.h

Add slot function declaration:

Slot functionexplain
newConnection()Execute this method when the client connects to the server;
disconnected()Execute this method when the client is disconnected;
readData()This method is executed when the data sent by the client is received
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
class QLocalServer;
class QLocalSocket;
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    ...
private slots:
    void on_pushButton_clicked();
    ///When the client connects to the server
    void newConnection();
    ///When the client disconnects
    void disconnected();
    ///When receiving data sent by the client
    void readData();

private:
    Ui::MainWindow *ui;
    QLocalServer *server;
    QLocalSocket *clientConnection;
};
#endif // MAINWINDOW_H

mainwindow.cpp

Include the necessary header files:

// mainwindow.cpp
#include <QLocalServer>
#include <QLocalSocket>

Constructor:

  • Instantiate QLocalServer,
  • newConnection() signal connecting to server
MainWindow::MainWindow(QWidget *parent) ...
{
    ...
    server = new QLocalServer(this);
    ...
    connect(server, &QLocalServer::newConnection, this, &MainWindow::newConnection);
}

newConnection() :

  • Get client connectionclientconnection
  • readyRead() signal connecting clientConnection
  • disconnected() signal connecting clientConnection
  • Enable button
void MainWindow::newConnection()
{
    clientConnection = server->nextPendingConnection();
    connect(clientConnection, &QLocalSocket::readyRead, this, &MainWindow::readData);
    connect(clientConnection, &QLocalSocket::disconnected, this, &MainWindow::disconnected);
    ui->pushButton->setEnabled(true);
}

readData() :

  • Read data from clientConnection;
  • Append data to text box
void MainWindow::readData()
{
    char buf[1024] = {0};
    clientConnection->read(buf, 1024);
    QString msg(buf);
    ui->plainTextEdit->appendPlainText(msg);
}

disconnected():

  • Delete connection
  • Disable button
void MainWindow::disconnected()
{
    clientConnection->deleteLater();
    ui->pushButton->setEnabled(false);
}

on_pushButton_clicked():

  • Send data to client
void MainWindow::on_pushButton_clicked()
{
    char *data = "hello, Python.";
    clientConnection->write(data);
}

Client programming (Python)

import os

try:
    fd = os.open('\\\\.\\pipe\\fortune', os.O_RDWR)
except FileNotFoundError:
    print('Error: Server not running, or pipe name dismatch.')
    raise FileNotFoundError
    
print('Wait recv...')

for k in  range(10):
    data = os.read(fd, 1024)
    print(data)
    d = b'Hello, Qt.'
    os.write(fd, d)

os.close(fd)

Topics: Python Qt