1. 程式人生 > >QLocalSocket與QLocalServer簡單演示本地程序通訊

QLocalSocket與QLocalServer簡單演示本地程序通訊

Qt中這種類似socket的手法,實質上是通過命名管道來實現的。演示程式碼很簡單:

client.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QLocalSocket>

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();

private:
    Ui::Widget *ui;
    QLocalSocket*client;
private slots:
    void on_connected();
    void on_disconnected();
};

#endif // WIDGET_H

client.cpp

#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    client = new QLocalSocket(this);
    connect(client,SIGNAL(connected()),this,SLOT(on_connected()));
    connect(client,SIGNAL(disconnected()),this,SLOT(on_disconnected()));
    client->connectToServer("testtest");
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_connected()
{
    QString a("i am client");
    client->write(a.toLatin1());
    client->flush();
}

void Widget::on_disconnected()
{
    qDebug()<<"on_disconnected";
}

 

server.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QLocalServer>

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();

private:
    Ui::Widget *ui;
    QLocalServer *server;

private slots:
    void on_connected();
    void on_readyRead();
};

#endif // WIDGET_H

server.cpp

#include "widget.h"
#include "ui_widget.h"
#include <QLocalSocket>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    server = new QLocalServer(this);
    connect(server,SIGNAL(newConnection()),this,SLOT(on_connected()));

    server->listen("testtest");

}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_connected()
{
    QLocalSocket *client = server->nextPendingConnection();
    connect(client,SIGNAL(readyRead()),this,SLOT(on_readyRead()));

}

void Widget::on_readyRead()
{
   QLocalSocket *client = static_cast<QLocalSocket*>(sender());
   ui->plainTextEdit->appendPlainText(client->readAll());
}