客户端
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QUdpSocket>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
Ui::MainWindow *ui;
QUdpSocket* m_pCSocket;
};
#endif // MAINWINDOW_H
main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
m_pCSocket = new QUdpSocket(this);
//要收消息就得绑定端口
m_pCSocket->bind(ui->lineEdit_cPort->text().toInt());
connect(ui->btnSend, &QPushButton::clicked, [=]{
//发消息
QString msg = "[client]:" + ui->textEdit_Msg->toPlainText();
m_pCSocket->writeDatagram(msg.toUtf8(), QHostAddress(ui->lineEdit_sIP->text()),
ui->lineEdit_sPort->text().toInt());
ui->textEdit_Record->append("[client]:" + msg);
ui->textEdit_Msg->clear();
});
connect(m_pCSocket, &QUdpSocket::readyRead, [=]{
qint64 len = m_pCSocket->pendingDatagramSize();
QByteArray array(len, 0);
m_pCSocket->readDatagram(array.data(), len);
ui->textEdit_Record->append(array);
});
}
MainWindow::~MainWindow()
{
delete ui;
}
服务端
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QUdpSocket>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
private:
Ui::Widget *ui;
QUdpSocket *m_pSSocket;
};
#endif // WIDGET_H
main.cpp
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}
widget.cpp
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
m_pSSocket = new QUdpSocket(this);
//要收消息就得绑定端口
m_pSSocket->bind(ui->lineEdit_sPort->text().toInt());
connect(ui->btnSend, &QPushButton::clicked, [=]{
//发消息
QString msg = "[server]:" + ui->textEdit_Msg->toPlainText();
m_pSSocket->writeDatagram(msg.toUtf8(), QHostAddress(ui->lineEdit_cIP->text()),ui->lineEdit_cPort->text().toInt());
ui->textEdit_Record->append("[server]:" + msg);
ui->textEdit_Msg->clear();
});
connect(m_pSSocket, &QUdpSocket::readyRead, [=]{
qint64 len = m_pSSocket->pendingDatagramSize();
QByteArray array(len, 0);
m_pSSocket->readDatagram(array.data(), len);
ui->textEdit_Record->append(array);
});
}
Widget::~Widget()
{
delete ui;
}
界面