Qt 之进程间通信(TCP/IP)

Qt 之进程间通信(TCP/IP)

简述

可以通过Qt提供的IPC使用TCP/IP,使用QtNetwork模块即可实现,TCP/IP在实现应用程序和进程内部通信或与远程进程间的通信方面非常有用。

QtNetwork模块提供的类能够创建基于TCP/IP的客户端与服务端应用程序。为实现底层的网络访问,可以使用QTcpSocket、QTcpServer和QUdpSocket,并提供底层网络类。还提供了使用常规协议实现网络操作的QNetworkRequest、QNetworkReply、QNetworkAccessManager。

| 版权声明:一去、二三里,未经博主允许不得转载。

QtNetwork

作为使用IPC的方法,TCP/IP可以使用多种类进行进程内部和外部的通信。

QtNetwork模块提供的类:

说明
QLocalServer 基于服务器的本地套接字的类
QLocalSocket 支持本地套接字的类
QNetworkAccessManager 处理从网络首发收据响应的类
QSocketNotifier 监控从网络通知消息的类
QSsl 在所有网络通信上用于SSL认证的类
QSslSocket 支持通过客户端和服务器端加密的套接字的类
QTcpServer 基于TCP的服务器端类
QTcpSocket TCP套接字
QUdpSocket UDP套接字

除表中所示,Qt提供的QtNetwork模块还支持多种协议。如果需要实现内部进程间的通信,建议使用QLocalSocket类。

下面我们来看一个示例,可以在Creator自带的示例中查找QLocalSocket或Local Fortune。

Server

首先,启动Server,这是必然的,服务端不开启,客户端怎么连接得上呢?

server = new QLocalServer(this);

// 告诉服务器监听传入连接的名字。如果服务器当前正在监听,那么将返回false。监听成功返回true,否则为false
if (!server->listen("fortune")) {
    QMessageBox::critical(this, tr("Fortune Server"),
                        tr("Unable to start the server: %1.")
                        .arg(server->errorString()));
    close();
    return;
}

fortunes << tr("You've been leading a dog's life. Stay off the furniture.")
         << tr("You've got to think about tomorrow.")
         << tr("You will be surprised by a loud noise.")
         << tr("You will feel hungry again in another hour.")
         << tr("You might have mail.")
         << tr("You cannot kill time without injuring eternity.")
         << tr("Computers are not intelligent. They only think they are.");

// 有新客户端进行连接时,发送数据
connect(server, SIGNAL(newConnection()), this, SLOT(sendFortune()));

// 发送数据
void Server::sendFortune()
{
    // 从fortunes中随机取出一段字符串然后进行写入。
    QByteArray block;
    QDataStream out(&block, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_4_0);
    out << (quint16)0;
    out << fortunes.at(qrand() % fortunes.size());
    out.device()->seek(0);
    out << (quint16)(block.size() - sizeof(quint16));

    // nextPendingConnection()可以返回下一个挂起的连接作为一个连接的QLocalSocket对象。
    QLocalSocket *clientConnection = server->nextPendingConnection();
    connect(clientConnection, SIGNAL(disconnected()),
            clientConnection, SLOT(deleteLater()));

    clientConnection->write(block);
    clientConnection->flush();
    clientConnection->disconnectFromServer();
}
   
   
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43

socket被当做server的孩子创建,这意味着,当QLocalServer对象被销毁时它也会被自动删除。这明显是一个删除对象的好主意,使用完成以后,避免了内存的浪费。

Client

启动客户端,连接到对应的服务器,如果连接不上,则进行错误处理。

socket = new QLocalSocket(this);

connect(getFortuneButton, SIGNAL(clicked()),
        this, SLOT(requestNewFortune()));
connect(socket, SIGNAL(readyRead()), this, SLOT(readFortune()));
connect(socket, SIGNAL(error(QLocalSocket::LocalSocketError)),
        this, SLOT(displayError(QLocalSocket::LocalSocketError)));

// 连接到服务器,abort()断开当前连接,重置socket。
void Client::requestNewFortune()
{
    getFortuneButton->setEnabled(false);
    blockSize = 0;
    socket->abort();
    socket->connectToServer(hostLineEdit->text());
}

// 读取服务器端发送的数据
void Client::readFortune()
{
    // 读取接收到的数据
    QDataStream in(socket);
    in.setVersion(QDataStream::Qt_4_0);

    if (blockSize == 0) {
        if (socket->bytesAvailable() < (int)sizeof(quint16))
            return;
        in >> blockSize;
    }

    if (in.atEnd())
        return;

    QString nextFortune;
    in >> nextFortune;

    // 如果当前的数据和收到的数据相同,则重新请求一次,因为是随机的字符串,所以肯定不会每次都相同。
    if (nextFortune == currentFortune) {
        QTimer::singleShot(0, this, SLOT(requestNewFortune()));
        return;
    }

    currentFortune = nextFortune;
    statusLabel->setText(currentFortune);
    getFortuneButton->setEnabled(true);
}

// 发生错误时,进行错误处理
void Client::displayError(QLocalSocket::LocalSocketError socketError)
{
    switch (socketError) {
    case QLocalSocket::ServerNotFoundError:
        QMessageBox::information(this, tr("Fortune Client"),
                                 tr("The host was not found. Please check the "
                                    "host name and port settings."));
        break;
    case QLocalSocket::ConnectionRefusedError:
        QMessageBox::information(this, tr("Fortune Client"),
                                 tr("The connection was refused by the peer. "
                                    "Make sure the fortune server is running, "
                                    "and check that the host name and port "
                                    "settings are correct."));
        break;
    case QLocalSocket::PeerClosedError:
        break;
    default:
        QMessageBox::information(this, tr("Fortune Client"),
                                 tr("The following error occurred: %1.")
                                 .arg(socket->errorString()));
    }

    getFortuneButton->setEnabled(true);
}
   
   
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73

更多参考

  • Qt之进程间通信(IPC)
  • Qt之进程间通信(Windows消息)
  • Qt之进程间通信(共享内存)
  • Qt之进程间通信(QProcess)
发布了414 篇原创文章 · 获赞 3930 · 访问量 571万+
        
展开阅读全文

加入我们

个人微信公众号:高效程序员

  • Qt 之进程间通信(TCP/IP)_第1张图片

如需商务合作,请在公众号后台留言。(备注:商务合作)


5.gif 一次合作,终生朋友! 3.gif

最新文章

  • 打包发布(超强推荐)
  • OSGI for C++ - 通往架构师之路
  • Log4j for C++ 实用指南
  • 公告【本博客暂停更新】
  • 2.14 一个特别的日子

分类专栏

  • C++ 设计模式 付费 23篇
  • Qt 中级进阶 付费 56篇
  • Qt 高级编程 付费 37篇
  • 《Qt 实战一二三》 140篇
  • 细说 QML 15篇
  • Linux 基础知识 39篇
  • 程序人生 10篇
  • Python 快速入门 57篇
  • C++/Qt 企业级开发 3篇
  • Qt 147篇
  • QML 14篇
  • C/C++ 6篇
  • Linux 39篇
  • Python 57篇
  • 音视频 2篇
  • Golang 3篇
  • CSS3 7篇
  • TCP/HTTP 1篇
  • 算法之美 3篇
  • 实用工具 7篇
  • 程序人生 11篇
  • 职场人必看 3篇
  • 超级福利 1篇

展开

归档

  • 2019年12月 3篇
  • 2019年3月 1篇
  • 2019年2月 1篇
  • 2018年12月 1篇
  • 2018年11月 3篇
  • 2018年8月 2篇
  • 2018年6月 1篇
  • 2018年5月 3篇
  • 2018年3月 2篇
  • 2018年2月 6篇
  • 2018年1月 1篇
  • 2017年11月 3篇
  • 2017年10月 3篇
  • 2017年9月 8篇
  • 2017年8月 4篇
  • 2017年7月 10篇
  • 2017年6月 8篇
  • 2017年5月 11篇
  • 2017年4月 11篇
  • 2017年3月 20篇
  • 2017年2月 2篇
  • 2017年1月 11篇
  • 2016年12月 10篇
  • 2016年11月 18篇
  • 2016年10月 29篇
  • 2016年9月 37篇
  • 2016年8月 23篇
  • 2016年7月 57篇
  • 2016年6月 27篇
  • 2016年5月 19篇
  • 2016年4月 9篇
  • 2016年3月 28篇
  • 2016年2月 5篇
  • 2016年1月 15篇
  • 2015年12月 12篇
  • 2015年11月 15篇

展开

最新评论

  • Qt 之 QDateTimeEdit

    weixin_46059463:嘻嘻,有完整文件吗?

  • Qt 之 QSS(样式表语法)

    qq_37657751:收费了?!花40才能看您的文章啊?!

  • OSGI for C++ - 通往...

    u011012932:是的,加我微信 wang_19890820。

  • Qt 之 QSS(黑色炫酷)

    MissYangIce:求分享 [email protected]

  • Qt 之等待提示框(QMovie)

    Lover_PHP:m_pLoadingLabel是啥?

你可能感兴趣的:(QT基础应用,Qt,《Qt,实战一二三》,Qt,Qt通信,Qt进程通信,QTcpSocket,QTcpServer)