我正试图编写一个程序,读取在linux中广播的UDP数据报。我是套接字编程的初学者。
我的代码是:如何使用QT编写基于UDP的C++套接字编程?
#include <QUdpSocket>
#include <iostream>
int main()
{
QUdpSocket *udpSocket ;
udpSocket= new QUdpSocket(0);
udpSocket->bind(QHostAddress::LocalHost, 3838);
udpSocket->connect(udpSocket, SIGNAL(readyRead()),
this, SLOT(readPendingDatagrams()));
while (1)
{
if (udpSocket->hasPendingDatagrams())
{
QByteArray datagram;
datagram.resize(udpSocket->pendingDatagramSize());
QHostAddress sender;
quint16 senderPort;
udpSocket->readDatagram(datagram.data(), datagram.size(),
&sender, &senderPort);
}
}
}
但在this
返回错误。
main.cpp:13:18: error: invalid use of ‘this’ in non-member function
我该怎么办?
没有'connect'就无法工作。它为你工作? – hamed 2012-03-29 13:33:23
@hamed:是的,它为我工作。我测试了Linux上的代码(以netcat作为发件人)。 – alexisdm 2012-03-29 14:01:55
但是既然你在你的问题中加了“广播”,我就相应地编辑了我的答案。 – alexisdm 2012-03-29 14:09:41