【发布时间】:2017-01-02 19:06:35
【问题描述】:
我想使用一些标准的QUdpSocket 方法,确切地说是read() 和readAll()。所以,根据QUdpSocket的文档:
如果要使用标准的
QIODevice函数read()、readLine()、write()等,必须首先通过调用connectToHost()将套接字直接连接到对等体。
我在bind()之后直接调用connectToHost():
socket.bind(QHostAddress::LocalHost, 14560);
socket.connectToHost(QHostAddress::LocalHost, 14560);
现在它可以读取,但不会发出readyRead() 信号。 QUdpSocket的QIODevice函数的正确使用方法是什么?
DeviceReader.h:
class DeviceReader : public QObject {
Q_OBJECT
public:
DeviceReader() {}
void setDevice(QIODevice * device) {
_device = device;
connect(device, &QIODevice::readyRead, this, &DeviceReader::onDataReceived);
}
void onDataReceived() {
qDebug() << "received: " << _device->readAll();
}
private:
QIODevice * _device;
};
main.cpp:
int main(int argc, char *argv[]) {
QCoreApplication a(argc, argv);
DeviceReader reader;
QUdpSocket socket;
socket.bind(QHostAddress::LocalHost, 14560);
socket.connectToHost(QHostAddress::LocalHost, 14560);
reader.setDevice(&socket);
return a.exec();
}
Qt 版本是 5.7.0 clang x64。操作系统:macOS Sierra 10.12.2。
【问题讨论】:
标签: c++ qt networking network-programming