QT += core gui
QT += network
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
CONFIG += c++17
# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
SOURCES += \
main.cpp \
widget.cpp
HEADERS += \
widget.h
FORMS += \
widget.ui
# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
注:.pro文件要加上QT +=network才可实现,且注意哦:若识别不到ui文件,可以重新构建实现。
(调到release再构建)
头文件:
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QTcpServer>
#include <QTcpSocket>
#define PORT 8000
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
private slots:
void newClientHandler();
private:
Ui::Widget *ui;
QTcpServer *server;
};
#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);
server =new QTcpServer;
server->listen(QHostAddress::AnyIPv4,PORT);
//客户端发起连接,server发出信号
connect(server,&QTcpServer::newConnection,this,&Widget::newClientHandler);
}
Widget::~Widget()
{
delete ui;
}
void Widget::newClientHandler()
{
//建立TCP连接
QTcpSocket *socket = server->nextPendingConnection();
socket->peerAddress();//获取客户端地址
socket->peerPort();//获取客户的端口号
ui->ipLineEdit->setText(socket->peerAddress().toString());
ui->portLineEdit->setText(QString::number(socket->peerPort()));
}
界面文件:
最后注意编译环境!!本人刚开始的时候调了半天才发现问题,千万别和我一样!