//发送各种UDP广播消息 void Widget::sndMsg(MsgType type, QString srvaddr) { QByteArray data; QDataStream out(&data, QIODevice::WriteOnly); QString address = getIP(); /*向要发送的数据中写入信息类型type、用户名(使用getUsr()函数获取), * 其中,type用于接收端区分信息类型,从而可以对不同类型的信息进行 * 不同的处理 */ out << type << getUsr(); switch(type) { case Msg: /* 对于普通的聊天消息Msg,首先判断发送的消息是否为空,如果为空, * 则进行警告;然后向发送的数据中写入本机的IP地址和用户输入的 * 聊天信息文本 */ if(ui->msgTxtEdit->toPlainText() == "") { QMessageBox::warning(0, tr("警告"), tr("发送内容不能为空"), QMessageBox::Ok); return; } out << address << getMsg(); ui->msgBrowser->verticalScrollBar()->setValue( ui->msgBrowser->verticalScrollBar()->maximum()); break; case UsrEnter: //对于新用户加入UsrEnter,只是简单地向数据中写入IP地址 out << address; break; case UsrLeft: //对于用户离开UsrLeft,不需要进行其他操作 break; case FileName: { //对于发送文件名FileName和拒绝接受文件Refuse,这里先不进行处理,稍后添加 int row = ui->usrTblWidget->currentRow(); QString clntaddr = ui->usrTblWidget->item(row, 1)->text(); out << address << clntaddr << fileName; break; } case Refuse: { out << srvaddr; break; } } udpSocket->writeDatagram(data, data.length(), QHostAddress::Broadcast, port); }
void Widget::sndMsg(MsgType type, QString srvaddr) { QByteArray data; QDataStream out(&data, QIODevice::WriteOnly); QString address = getIP(); out << type << getUsr(); switch(type) { case Msg : if (ui->msgTxtEdit->toPlainText() == "") { QMessageBox::warning(0,tr("警告"),tr("发送内容不能为空"),QMessageBox::Ok); return; } out << address << getMsg(); ui->msgBrowser->verticalScrollBar()->setValue(ui->msgBrowser->verticalScrollBar()->maximum()); break; case UsrEnter : out << address; break; case UsrLeft : break; case FileName : { int row = ui->usrTblWidget->currentRow(); QString clntaddr = ui->usrTblWidget->item(row, 1)->text(); out << address << clntaddr << fileName; break; } case Refuse : out << srvaddr; break; } udpSocket->writeDatagram(data,data.length(),QHostAddress::Broadcast, port); }