|
这是代码:
#include "widget.h"
#include "ui_widget.h"
#include <QHostAddress>
Widget::Widget(QWidget *parent) Widget(parent),ui(new Ui::Widget)
{
ui->setupUi(this);
udpSocket = new QUdpSocket(this);
udpSocket->bind(QHostAddress::AnyIPv4, 8888);
udpSocket->joinMulticastGroup( QHostAddress("224.0.2.2") );
setWindowTitle("服务器端口:8888");
connect(udpSocket, &QUdpSocket::readyRead, this, &Widget::dealMsg);
}
void Widget::dealMsg()
{
char buf[1024] = {0};
QHostAddress cliAddr; //对方地址
quint16 port; //对方端口
qint64 len = udpSocket->readDatagram(buf, sizeof(buf), &cliAddr, &port);
if(len > 0)
{
QString str = QString("[%1:%2] %3").arg(cliAddr.toString()).arg(port).arg(buf);
ui->textEdit->setText(str);
}
}
Widget::~Widget()
{
delete ui;
}
|
|