QT网络通信TCP客户端实现详解

本文实例为大家分享了QT网络通信TCP客户端实现的具体代码,供大家参考,具体内容如下

QT中基于TCP套接字的网络通信需要用到两个类

  • QTcpServer:服务器类,用于监听客户端连接和客户端建立连接
  • QTcpSocket:通信套接字类,客户端和服务端都需要使用*

这两个类都属于网络通信的network
需要在工程路径下添加network

QT += core gui network

服务器

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->port->setText("8899");
    ui->ip->setText("127.0.0.1");
    setWindowTitle("客户端");
    m_tcp = new QTcpSocket(this);

    connect(m_tcp,&QTcpSocket::readyRead,this,[=](){
        QByteArray data = m_tcp->readAll();
        ui->record->append("服务端:"+data);

    });
     connect(m_tcp,&QTcpSocket::disconnected,this,[=]()
    {
         ui->connect->setEnabled(true);
         ui->disconnect->setDisabled(true);
        m_tcp->close();
 //       m_tcp->deleteLater();//状态释放
        m_status->setPixmap(QPixmap(":/red.png").scaled(20,20));
        ui->record->append("断开连接");

    });
     connect(m_tcp,&QTcpSocket::connected,this,[=](){
       m_status->setPixmap(QPixmap(":/green.png").scaled(20,20));
       ui->connect->setDisabled(true);
       ui->disconnect->setEnabled(true);
       ui->record->append("连接成功");
     });
    //
    ui->disconnect->setDisabled(true);
    m_status = new QLabel;
    m_status->setPixmap(QPixmap(":/red.png").scaled(20,20));
    ui->statusBar->addWidget(new QLabel("连接状态:"));
    ui->statusBar->addWidget(m_status);

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_sendMsg_clicked()
{
   QString msg = ui->message->toPlainText();
    m_tcp->write(msg.toUtf8());
    ui->record->append("客户端:"+msg);

}

void MainWindow::on_connect_clicked()
{
    QString ip=ui->ip->text();

    unsigned short port=ui->port->text().toUShort();

    m_tcp->connectToHost(QHostAddress(ip),port);

    ui->connect->setEnabled(false);
    ui->disconnect->setDisabled(false);

}

void MainWindow::on_disconnect_clicked()
{

    m_tcp->close();
    ui->connect->setEnabled(true);
    ui->disconnect->setDisabled(true);

}

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QTcpSocket>
#include <Qlabel>
#include <QHostAddress>
namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private slots:

    void on_sendMsg_clicked();

    void on_connect_clicked();

    void on_disconnect_clicked();

private:
    Ui::MainWindow *ui;
    QTcpSocket  *m_tcp;
    QLabel     *m_status;
};

#endif // MAINWINDOW_H

ui文件

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>428</width>
    <height>606</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <widget class="QWidget" name="centralWidget">
   <layout class="QVBoxLayout" name="verticalLayout">
    <item>
     <widget class="QWidget" name="widget" native="true">
      <layout class="QGridLayout" name="gridLayout">
       <item row="1" column="0">
        <widget class="QLabel" name="label_3">
         <property name="text">
          <string>IP:</string>
         </property>
        </widget>
       </item>
       <item row="0" column="0">
        <widget class="QLabel" name="label">
         <property name="text">
          <string>端口:</string>
         </property>
        </widget>
       </item>
       <item row="1" column="1">
        <widget class="QLineEdit" name="ip"/>
       </item>
       <item row="1" column="2">
        <widget class="QPushButton" name="disconnect">
         <property name="text">
          <string>断开连接</string>
         </property>
        </widget>
       </item>
       <item row="0" column="1">
        <widget class="QLineEdit" name="port"/>
       </item>
       <item row="0" column="2">
        <widget class="QPushButton" name="connect">
         <property name="text">
          <string>连接服务器</string>
         </property>
        </widget>
       </item>
      </layout>
     </widget>
    </item>
    <item>
     <widget class="QGroupBox" name="groupBox">
      <property name="title">
       <string>历史信息</string>
      </property>
      <layout class="QHBoxLayout" name="horizontalLayout_2">
       <item>
        <widget class="QTextEdit" name="record"/>
       </item>
      </layout>
     </widget>
    </item>
    <item>
     <widget class="QGroupBox" name="groupBox_2">
      <property name="title">
       <string>发送信息</string>
      </property>
      <layout class="QHBoxLayout" name="horizontalLayout_3">
       <item>
        <widget class="QTextEdit" name="message"/>
       </item>
      </layout>
     </widget>
    </item>
    <item>
     <widget class="QWidget" name="widget_2" native="true">
      <layout class="QHBoxLayout" name="horizontalLayout_4">
       <item>
        <spacer name="horizontalSpacer_2">
         <property name="orientation">
          <enum>Qt::Horizontal</enum>
         </property>
         <property name="sizeHint" stdset="0">
          <size>
           <width>136</width>
           <height>20</height>
          </size>
         </property>
        </spacer>
       </item>
       <item>
        <widget class="QPushButton" name="sendMsg">
         <property name="text">
          <string>发送信息</string>
         </property>
        </widget>
       </item>
       <item>
        <spacer name="horizontalSpacer">
         <property name="orientation">
          <enum>Qt::Horizontal</enum>
         </property>
         <property name="sizeHint" stdset="0">
          <size>
           <width>135</width>
           <height>20</height>
          </size>
         </property>
        </spacer>
       </item>
      </layout>
     </widget>
    </item>
   </layout>
  </widget>
  <widget class="QMenuBar" name="menuBar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>428</width>
     <height>23</height>
    </rect>
   </property>
  </widget>
  <widget class="QToolBar" name="mainToolBar">
   <attribute name="toolBarArea">
    <enum>TopToolBarArea</enum>
   </attribute>
   <attribute name="toolBarBreak">
    <bool>false</bool>
   </attribute>
  </widget>
  <widget class="QStatusBar" name="statusBar"/>
 </widget>
 <layoutdefault spacing="6" margin="11"/>
 <resources/>
 <connections/>
</ui>

ui界面

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • QT编写tcp通信工具(Client篇)

    本文实例为大家分享了QT编写tcp通信工具的具体实现代码,Client篇,供大家参考,具体内容如下 1.说明 使用qt写一个类似网上常见的网络调试工具.此篇为Client端.下一遍再写Server端. 2.基本流程 Client端相对简单:创建QTcpSocket对象,为对象的readyRead,error,connected(可选)分别写槽函数,以处理读数据,错误,连接成功三个事件. 连接使用对象的connectToHost方法,断开使用disconnectFromHost方法. 程序不做编码

  • QT编写tcp通信工具(Server端)

    本文实例为大家分享了QT编写Server端的tcp通信工具的具体代码,供大家参考,具体内容如下 1.说明 使用qt写一个类似网上常见的网络调试工具.此篇为Server端.Client端在上一篇. 2.基本流程 新建QTcpServer对象,为其newConnection信号写槽函数.此为新的Client连接信号,在其对应槽函数里使用nextPendingConnection方法获取Client对象,并为Client添加readyRead(读数据),disconnected(断开连接)两个信号写槽

  • QT5实现简单的TCP通信的实现

    目录 一.客户端 二.服务器 三.运行结果 这段时间用到了QT的TCP通信,做了初步的学习与尝试,编写了一个客户端和服务器基于窗口通信的小例程. 使用QT的网络套接字需要.pro文件中加入一句: QT += network 一.客户端 1.客户端的代码比服务器稍简单,总的来说,使用QT中的QTcpSocket类与服务器进行通信只需要以下5步: (1)创建QTcpSocket套接字对象 socket = new QTcpSocket(); (2)使用这个对象连接服务器 socket->connec

  • Qt网络编程实现TCP通信

    Qt网络编程实现TCP通信,供大家参考,具体内容如下 标签(空格分隔): Tcp通信 一.Tcp简介 (1)TCP(Transmission Control Protocol,传输控制协议)TCP是一个用于数据传输的传输层网络协议,多个网络协议包括(HTTP和FTP都是基于TCP协议),TCP是面向数据流和连接的可靠的传输协议,它区别于传输层的另外一个协议UDP(具体可看—Qt简单实现UDP通信) . (2)QTcpSocket继承自QAbstractSocket,与QUdpSocket传输的数

  • 基于QT的TCP通信服务的实现

    目录 一.结构 1.1 套接字 1.2 socket通信流程 1.3 QTcpsocket 1.4 QTcpServer 二.设计UI 2.1 客户端UI 2.2 服务器端UI 三.核心代码 四.效果图 一.结构 1.1 套接字 应用层通过传输层进行数据通信时,TCP和UDP会遇到同时为多个应用程序进程提供并发服务的问题.多个TCP连接或多个应用程序进程可能需要 通过同一个TCP协议端口传输数据.为了区别不同的应用程序进程和连接,许多计算机操作系统为应用程序与TCP/IP协议交互提供了称为套接字

  • Qt TCP网络通信学习

    TCP简介: Transmission Control Protocol,传输控制协议 .用于数据传输的低层网络协议,多个物联网协议都是基于TCP协议的.它是一个面向数据流和连接的可靠传输协议. TCP头部格式: QTcpSocket类为TCP提供了一个接口,继承自QAbstractSocket.可实现POP3.SMTP.NNTP等标准的网络协议,也可以实现自定义的网络协议.异步工作,依靠事件循环来检测到来的数据,并且自动刷新输出的数据.而QAbstractSocket继承自QIODevice,

  • QT网络编程Tcp下C/S架构的即时通信实例

    先写一个客户端,实现简单的,能加入聊天,以及加入服务器的界面. #ifndef TCPCLIENT_H #define TCPCLIENT_H #include <QDialog> #include <QListWidget> #include <QLineEdit> #include <QPushButton> #include <QLabel> #include <QGridLayout> #include <QtNetWo

  • QT网络通信TCP客户端实现详解

    本文实例为大家分享了QT网络通信TCP客户端实现的具体代码,供大家参考,具体内容如下 QT中基于TCP套接字的网络通信需要用到两个类 QTcpServer:服务器类,用于监听客户端连接和客户端建立连接 QTcpSocket:通信套接字类,客户端和服务端都需要使用* 这两个类都属于网络通信的network需要在工程路径下添加network QT += core gui network 服务器 mainwindow.cpp #include "mainwindow.h" #include

  • Qt中TCP协议通信详解

    TCP协议是经常使用的通信方式.在QT中做了非常友好的封装,使用非常方便. 需要添加的模块:network Qt中的TCP类:QTcpSocket , QTcpServer 常用函数介绍 连接目标地址和端口 virtual void QTcpSocket ::connectToHost(const QHostAddress &address, quint16 port, OpenMode mode = ReadWrite); 发送数据 inline qint64 QTcpSocket ::wri

  • 基于python中的TCP及UDP(详解)

    python中是通过套接字即socket来实现UDP及TCP通信的.有两种套接字面向连接的及无连接的,也就是TCP套接字及UDP套接字. TCP通信模型 创建TCP服务器 伪代码: ss = socket() # 创建服务器套接字 ss.bind() # 套接字与地址绑定 ss.listen() # 监听连接 inf_loop: # 服务器无限循环 cs = ss.accept() # 接受客户端连接 comm_loop: # 通信循环 cs.recv()/cs.send() # 对话(接收/发

  • Python基础教程之tcp socket编程详解及简单实例

    Python tcp socket编程详解 初学脚本语言Python,测试可用的tcp通讯程序: 服务器: #!/usr/bin/env python # -*- coding: utf-8 -*- import socket import threading import time def tcplink(sock, addr): print('Accept new connection from %s:%s...' % addr); sock.send(b'Welcome!!!'); whi

  • vue3+electron12+dll开发客户端配置详解

    当前使用的版本为 @vue/cli4 创建的 vue3.0 + typescript + electron 12 版本创建,其他版本暂未测试.网上资料良莠不齐,因此花费时间依次试验,达到一个目前最优解. 修改仓库源 由于electron版本的未知性,可能存在serve可用而build之后打开白屏的情况,因此需要谨慎对待.最好在版本可用的情况下commit一个版本,方便代码回滚,如果谁有更好的资料希望共享. 在开始配置前,可以将yarn和npm的rc文件稍作修改,使用命令或者文件直接修改.npmr

  • C/C++ Qt数据库SqlRelationalTable关联表详解

    在上一篇博文中详细介绍了SqlTableModle组件是如何使用的,本篇博文将介绍SqlRelationalTable关联表组件,该组件其实是SqlTableModle组件的扩展类,SqlRelationalTable组件可以关联某个主表中的外键,例如将主表中的某个字段与附加表中的特定字段相关联起来,QSqlRelation(关联表名,关联ID,名称)就是用来实现多表之间快速关联的. 首先我们创建两张表,一张Student表存储学生名字以及学生课程号,另一张Departments存储每个编号所对

  • Qt使用QWT绘制柱状图详解

    目录 1:设置QChart的整体背景色 2:设置有效区域的背景色 3:设置X.Y坐标轴数据 4:设置网格线 5:插入实际数据 6:X轴刻度值优化 7:设置X轴文本偏移 8:设置每个柱状体的宽度 9:设置每个柱状体的偏移量 10:修改鼠标的显示状态 有的时候我们会遇到这样一种功能,需要在柱状图中显示不同颜色的柱状体,每个主状态代表的状态不同,那么如果只是用简单的QChart是难以实现的. QT中提供了一个叫做QWT的库.QWT,全称是Qt Widgets for Technical Applica

  • Qt+OpenCV实现目标检测详解

    目录 一.创建项目&UI设计 二.代码与演示 演示效果 拓展阅读 一.创建项目&UI设计 创建项目,UI设计如下 文件类型判断 简单的判断文件类型 QString file("sample.jpg"); if (file.contains(".jpg") || file.contains(".bmp") || file.contains(".png")) qDebug()<<"这是图片.&

  • Qt+FFMPEG实现循环解码详解

    目录 一.结果 二.解码准备工作+循环解码相关操作 videodecode.h .cpp main.cpp 一.结果 可以设置延时函数-----遍历每一帧的信息进行打印 25(fps)*30(秒)=750帧 二.解码准备工作+循环解码相关操作 videodecode.h .cpp #ifndef VIDEODECODE_H #define VIDEODECODE_H #include <QObject> //当前C++兼容C语言 extern "C" { //avcodec

  • SpringCloud OpenFeign与Ribbon客户端配置详解

    目录 一.前言 二.OpenFeign与Ribbon配置 1.OpenFeign默认处理请求超时时间 1.1.模拟处理请求0.5秒 1.2.模拟处理请求1秒 2.Ribbon配置 2.1.配置请求处理超时5秒 2.2.模拟请求处理5秒 3.OpenFeign配置 3.1.配置请求处理超时6秒 3.2.OpenFeign配置对全部服务有效 3.3.针对某个服务 一.前言 OpenFeign为微服务架构下服务之间的调用提供了解决方案,OpenFeign是一种声明式.模板化的HTTP客户端.在Spri

随机推荐