qt 用UDP广播后,无法接受到广播的内容怎么回事,求指教。

#include "mainwindow.h"
#include "ui_mainwindow.h"
int port = 8888;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);

}

MainWindow::~MainWindow()
{
delete ui;
}

void MainWindow::recvmydata()//接收数据
{
//char buf[1024]={0};
while(udpSocket->hasPendingDatagrams())
{
QByteArray datagram;
datagram.resize(udpSocket->pendingDatagramSize());
udpSocket->readDatagram(datagram.data(),datagram.size());

       // udpSocket->readDatagram(buf,sizeof(buf));
        ui->textBrowser->append(datagram.data());
        //memset(buf,0,sizeof(buf));
    }

}
void MainWindow::mysenddata()//发送数据
{
QString ip = ui->ip_lineEdit->text();
QString name = ui->name_lineEdit->text();
QString txt=ui->plainTextEdit->toPlainText();
char buf[1024]={0};
strcpy(buf,txt.toStdString().data());
//QHostAddress::Broadcast *serip=new QHostAddress::Broadcast();
//serip->Q("192.168.23.255");
//udpSocket->writeDatagram(txt,txt.length(),QHostAddress::Broadcast,8888);
udpSocket->writeDatagram(buf,strlen(buf),QHostAddress::Broadcast, 8888);
//delete serip;
ui->plainTextEdit->clear();

}

void MainWindow::on_pushButton_2_clicked()
{
QString ip = ui->ip_lineEdit->text();
QString name = ui->name_lineEdit->text();
if(ip.isEmpty()){
QMessageBox::information(this,"请输入IP地址","IP地址不能为空!");
}else if (name.isEmpty()){
QMessageBox::information(this,"请输入名字","名字不能为空!");
}else if(ip.isEmpty() && name.isEmpty()){
QMessageBox::information(this,"请输入名字和IP","名字和不能为空!");
}else{
QMessageBox::information(this,"欢迎加入聊天室","欢迎"+name+"加入聊天室");
udpSocket = new QUdpSocket(this);
udpSocket->bind(8888,QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint);
connect(udpSocket,SIGNAL(readyRead()),this,SLOT(recvmydata()));
connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(mysenddata()));
}
}

为要写一个聊天室UDP的

1个回答

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!