//Please reproduce under macOS, there are no issues with Windows void chatSocket::init() { QHostInfo::lookupHost("www.yourweb.com", this, SLOT(initSocket(QHostInfo))); } void chatSocket::initSocket(const QHostInfo &host) { if (host.error() != QHostInfo::NoError) { return; } //只取第一个 m_hostAddr = host.addresses()[0]; m_udpSocket = new QUdpSocket(this); connect(m_udpSocket, SIGNAL(readyRead()), this, SLOT(readPendingDatagrams())); //初始化完成 emit winMsg(MSG_INIT_FINISH, QStringLiteral("网络ok")); } bool chatSocket::SendData(char *text, int len) { if (m_udpSocket != nullptr) { m_udpSocket->writeDatagram(text, len,m_hostAddr, 6060); return true; } return false; } void chatSocket::readPendingDatagrams() { while ((m_udpSocket!=nullptr) && m_udpSocket->hasPendingDatagrams()) { //Returns the size of the first pending UDP datagram. If there is no datagram available, this function returns -1. int len = m_udpSocket->pendingDatagramSize(); if (len < 0) { break; } char * data = new char[len+1]; data[len] = '\0'; int msglen = m_udpSocket->readDatagram(data,len); if (msglen <= 0) { delete[]data; } else { // do other work } } }