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

演示

服务端

相关推荐
blasit5 小时前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
郑州光合科技余经理5 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1235 天前
matlab画图工具
开发语言·matlab
dustcell.5 天前
haproxy七层代理
java·开发语言·前端
norlan_jame5 天前
C-PHY与D-PHY差异
c语言·开发语言
多恩Stone5 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
gihigo19985 天前
基于TCP协议实现视频采集与通信
网络协议·tcp/ip·音视频
QQ4022054965 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
遥遥江上月5 天前
Node.js + Stagehand + Python 部署
开发语言·python·node.js
m0_531237175 天前
C语言-数组练习进阶
c语言·开发语言·算法