gpt4 book ai didi

c++ - QUdpSocket:程序发送但不接收

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:42:28 24 4
gpt4 key购买 nike

我对 QUdpSocket 有疑问。我想创建一个简单的程序来使用 UDP 协议(protocol)发送和接收数据。我已经阅读了许多类似的主题,但我没有找到解决的方法。通信仅适用于 QHostAdress::LocalHost,然后我提供与发送相同的数据,但如果我想将数据发送到外部设置的具体地址,例如 194.181.161.134 ,那是行不通的。这意味着数据已发送但我无法接收。这是我的代码:

class Okno_GL : public QMainWindow
{
Q_OBJECT
public:
explicit Okno_GL(QWidget *parent = 0);
QWidget *wg;
QPushButton *pb;
QPushButton *pl;
QGridLayout *gr;
QUdpSocket *socket;
QHostAddress host;
QHostAddress bcast;


signals:

public slots:
void SLOT_Write();
void SLOT_load();
};

class Receiver : public QObject
{
Q_OBJECT
public:
Receiver();

QUdpSocket *udpSocket;
public slots:
void SLOT_processPendingDatagrams();
void SLOT_StCh(QAbstractSocket::SocketState state);
};

Okno_GL::Okno_GL(QWidget *parent) :
QMainWindow(parent)
{
pb = new QPushButton("write" , this);
pl = new QPushButton("read" , this);
wg = new QWidget(this);
setCentralWidget(wg);
gr = new QGridLayout(wg);
gr->addWidget(pb);
gr->addWidget(pl);
socket = new QUdpSocket(this);

connect(pb , SIGNAL(clicked()) , SLOT(SLOT_Write()));
connect(pl , SIGNAL(clicked()) , SLOT(SLOT_load()));

}

void Okno_GL::SLOT_Write()
{
QByteArray datagram = "gS";
int send;
send = socket->writeDatagram(datagram.data(), QHostAddress("194.181.161.134"), 1200);
}

void Okno_GL::SLOT_load()
{

}


Receiver::Receiver()
{


udpSocket = new QUdpSocket(this);
connect(udpSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)) , this , SLOT(SLOT_StCh(QAbstractSocket::SocketState)));

if(udpSocket->bind(QHostAddress::Any , 1200))
{
qd "bind";
}
else
{
qd "not bind";
}

}

void Receiver::SLOT_processPendingDatagrams()
{
qd "receiver";
QByteArray datagram;

do {
datagram.resize(udpSocket->pendingDatagramSize());
udpSocket->readDatagram(datagram.data(), datagram.size());
} while (udpSocket->hasPendingDatagrams());

qd "datagram" << datagram;
}

void Receiver::SLOT_StCh(QAbstractSocket::SocketState state)
{
qd "slot" << state;

QByteArray datagram = "gS";
if ( state == QAbstractSocket::BoundState ) {

connect(udpSocket, SIGNAL(readyRead()), this, SLOT(SLOT_processPendingDatagrams()) , Qt::QueuedConnection);
}

}

最佳答案

您应该使用 write() 而不是 writeDatagram()

qint64 QUdpSocket::writeDatagram (const char * data, qint64 size, const QHostAddress & address, quint16 port)

Warning: Calling this function on a connected UDP socket may result in an error and no packet being sent. If you are using a connected socket, use write() to send datagrams.

关于c++ - QUdpSocket:程序发送但不接收,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26473353/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com