使用UDP其实不用区分服务器端和客户端,直接用同一程序就能建立连接,下面直接贴出代码
1、头文件
#ifndef SERVERWIDGET_H #define SERVERWIDGET_H #include <QWidget> #include <QUdpSocket> //UDP套接字 namespace Ui { class ServerWidget; } class ServerWidget : public QWidget { Q_OBJECT public: explicit ServerWidget(QWidget *parent = 0); ~ServerWidget(); void dealMsg(); // 处理对方发过来的数据 private slots: void on_buttonSend_clicked(); void on_buttonClose_clicked(); private: Ui::ServerWidget *ui; QUdpSocket *udpSocket; }; #endif // SERVERWIDGET_H
2、cpp文件
#include "serverwidget.h" #include "ui_serverwidget.h" #include <QHostAddress> ServerWidget::ServerWidget(QWidget *parent) : QWidget(parent), ui(new Ui::ServerWidget) { ui->setupUi(this); setWindowTitle("服务器:8899"); udpSocket = NULL; //分配空间,指定父对象 udpSocket = new QUdpSocket(this); //绑定 udpSocket->bind(8899); //当对方成功发送数据过来 //自动触发readyRead connect(udpSocket, &QUdpSocket::readyRead, this, &ServerWidget::dealMsg); } ServerWidget::~ServerWidget() { delete ui; } //处理对方发过来的数据 void ServerWidget::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->textEditRead->setText(str); } } //发送数据 void ServerWidget::on_buttonSend_clicked() { if(udpSocket == NULL){ return; } //先获取对方的IP和端口 QString ip = ui->lineEditIp->text(); qint16 port = ui->lineEditPort->text().toInt(); //获取编辑区内容 QString contentStr = ui->textEditRead->toPlainText(); //给指定的IP发送数据 udpSocket->writeDatagram(contentStr.toUtf8(), QHostAddress(ip), port); } //关闭连接 void ServerWidget::on_buttonClose_clicked() { if(udpSocket == NULL){ return; } udpSocket->disconnectFromHost(); udpSocket->close(); }
3、最终实现的效果如下图
版权声明:
此文为本站源创文章[或由本站编辑从网络整理改编],
转载请备注出处:
[狂码一生]
https://www.sindsun.com/articles/16/85
[若此文确切存在侵权,请联系本站管理员进行删除!]
--THE END--