简体   繁体   中英

Use QT to read from socket

I want to use IPC in order to exchange messages between two separate applications. The first one is a BASH script which is fired when a specific udev rule is activated (in Ubuntu Linux), and the other one is a simple Qt 5.7 console application, which acts as a server.

I already have the Qt server working and printing a message when it accepts a connection to the specified socket. What I'm trying to achieve now, is to make the server do something not when it accepts a connection, but when it receives a certain "message". Any ideas on how to do it?

Below is my code:

server.cpp

#include "server.h"

Server::Server() : QThread()
{
    m_server = new QLocalServer(this);
    m_server->listen("somesocket.sock");
    connect(m_server, &QLocalServer::newConnection, this, &Server::testFunction);
}

Server::~Server()
{
    m_server->removeServer("somesocket.sock");
}

void Server::run()
{
}

void Server::testFunction(){
    qDebug() << "Sth happened!";
    return;
}

server.h

#ifndef SERVER_H
#define SERVER_H

#include <QThread>
#include <QObject>
#include <QDebug>
#include <QLocalServer>

class Server : public QThread
{
public:
    Server();
    ~Server();
    void run();
    void testFunction();
private:
     QLocalServer *m_server;
signals:
    void connectionEstablished(bool);
};

#endif // SERVER_H

You could connect to readyRead signal, and then check received message, like in this example:

connect( this, SIGNAL(readyRead()), SLOT(readClient()) );

void readClient()
{
    QTextStream ts( this );
    int line = 0;

    while ( canReadLine() ) {
        QString str = ts.readLine();

        if(str == "someSpecialMessage")
        {
           //...
        }

        line++;
    }
}

for more informations about this signal, see documentation: http://doc.qt.io/qt-5/qiodevice.html#readyRead

This is also an example of client and server applications in Qt, using QSocket and QServerSocket: https://doc.qt.io/archives/3.3/clientserver-example.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM