【qt】基于tcp的服务端编写

实现服务端,连接后拿到客户端ip地址和端口号

ui设计

修改对应行编辑对象名,修改客户端ip为clientip,客户端端口号为clientport

代码实现

1.网络通信需要加network

2.包含头文件

3.定义一个QTcpserver变量,并初始化

4.服务端监听,以及服务器收到链接信号,建立新链接

5.编写槽函数

源码分享

.h

c 复制代码
#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include<QTcpSocket>
#include<QTcpServer>
#define PORT 8080
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 deal();
private:
    Ui::Widget *ui;
    QTcpServer *server;
};
#endif // WIDGET_H

.cpp

c 复制代码
#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);
    connect(server,&QTcpServer::newConnection,this,&Widget::deal);
}

Widget::~Widget()
{
    delete ui;
}
void Widget::deal()
{

    QTcpSocket* socket=server->nextPendingConnection();
    ui->clientip->setText(socket->peerAddress().toString());
    ui->clientport->setText(QString::number(socket->peerPort()));
}

演示

服务端

相关推荐
睡美人的小仙女1273 小时前
Threejs加载环境贴图报错Bad File Format: bad initial token
开发语言·javascript·redis
rayufo4 小时前
【工具】列出指定文件夹下所有的目录和文件
开发语言·前端·python
RANCE_atttackkk4 小时前
[Java]实现使用邮箱找回密码的功能
java·开发语言·前端·spring boot·intellij-idea·idea
缺点内向4 小时前
C#编程实战:如何为Word文档添加背景色或背景图片
开发语言·c#·自动化·word·.net
一起养小猫4 小时前
Flutter for OpenHarmony 实战:记账应用数据统计与可视化
开发语言·jvm·数据库·flutter·信息可视化·harmonyos
zhougl9965 小时前
Java 所有关键字及规范分类
java·开发语言
java1234_小锋5 小时前
Java高频面试题:MyISAM索引与InnoDB索引的区别?
java·开发语言
2501_944525545 小时前
Flutter for OpenHarmony 个人理财管理App实战 - 支出分析页面
android·开发语言·前端·javascript·flutter
qq_417129255 小时前
C++中的桥接模式变体
开发语言·c++·算法
开源技术5 小时前
如何将本地LLM模型与Ollama和Python集成
开发语言·python