【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()));
}

演示

服务端

相关推荐
network_tester1 小时前
IXIA XM2网络测试仪电源模块损坏维修方法详解
网络·网络协议·tcp/ip·http·https·信息与通信·信号处理
郑州光合科技余经理1 小时前
同城系统海外版:一站式多语种O2O系统源码
java·开发语言·git·mysql·uni-app·go·phpstorm
buyutang_1 小时前
Linux网络编程:Socket套接字编程概念及常用API接口介绍
linux·服务器·网络·tcp/ip
一只乔哇噻1 小时前
java后端工程师+AI大模型开发进修ing(研一版‖day60)
java·开发语言·人工智能·学习·语言模型
LNN20221 小时前
Linuxfb+Qt 输入设备踩坑记:解决 “节点存在却无法读取“ 问题
开发语言·qt
qq_401700411 小时前
Qt单实例程序-----禁止程序多开
qt
foxsen_xia2 小时前
go(基础06)——结构体取代类
开发语言·算法·golang
巨人张2 小时前
C++火柴人跑酷
开发语言·c++
ID_180079054732 小时前
基于 Python 的 Cdiscount 商品详情 API 调用与 JSON 核心字段解析(含多规格 SKU 提取)
开发语言·python·json
悟能不能悟3 小时前
Caused by: java.sql.SQLException: ORA-28000: the account is locked怎么处理
java·开发语言