前言

TCP传输控制协议 是一个可靠的(相对于UDP),面向流,面向连接的运输协议。
Socket 俗称“套接字”。就是对网络中不同主机上的应用进程之间进行双向通信的端点的抽象。一个套接字就是网络上进程通信的一端,提供了应用层进程利用网络协议交换数据的机制。从所处的地位来讲,套接字上联应用进程,下联网络协议栈,是应用程序通过网络协议进行通信的接口,是应用程序与网络协议根进行交互的接口。
套接字Socket=(IP地址:端口号) QTcpSocket传输的过程是连续的(对于网络的要求是比较高的,稳定)。TCP编程一般分成客户端和服务器端,即C/S(Client/Server)架构。

实现部分–服务端

头文件实现


#ifndef MAINTCPSERVER_H
#define MAINTCPSERVER_H#include <QMainWindow>
#include <QLabel>
#include <QTcpServer>
#include <QTcpSocket>
#include <QHostInfo>namespace Ui {class MainTcpServer;
}class MainTcpServer : public QMainWindow
{Q_OBJECTpublic:explicit ExTcpServer(QWidget *parent = nullptr);~ExTcpServer();private:QString getLocalIp();      //获取本机 IPprotected:void closeEvent(QCloseEvent* event);private slots:
//UI的槽函数void on_actStart_triggered();      //开始监听void on_actStop_triggered();       //停止监听void on_actClear_triggered();      //清除文本框内容void on_actQuit_triggered();       //退出程序void on_btnSend_clicked();         //发送消息//自定义的槽函数void onSocketReadyRead();          //读取 socket 传入时候的数据void onClientConnected();          //client socket connetedvoid onClientDisonnected();        //client socket disconnetedvoid onNewConnection();            //QTcpServer 的 newConnect() 信号void onSocketStateChange(QAbstractSocket::SocketState socketState);private:Ui::ExTcpServer *ui;QLabel* m_labListen;QLabel* m_labSocket;QTcpServer* m_tcpServer;QTcpSocket* m_tcpSocket;
};#endif // MAINTCPSERVER_H

CPP 文件实现


#include "MainTcpServer.h"
#include "ui_MainTcpServer.h"MainTcpServer::MainTcpServer(QWidget *parent) :QMainWindow(parent),ui(new Ui::MainTcpServer)
{ui->setupUi(this);m_labListen = new QLabel("监听状态:");m_labSocket = new QLabel("socket状态:");m_labListen->setMidLineWidth(200);m_labSocket->setMinimumWidth(200);ui->statusBar->addWidget(m_labListen);ui->statusBar->addWidget(m_labSocket);QString localeIp = getLocalIp();setWindowTitle(windowTitle() + "---IP地址:" + localeIp);ui->comboBox->addItem(localeIp);m_tcpServer = new QTcpServer(this);connect(m_tcpServer, SIGNAL(newConnection()), this, SLOT(onNewConnection()));
}MainTcpServer::~MainTcpServer()
{delete ui;
}QString MainTcpServer::getLocalIp()
{QString hostName = QHostInfo::localHostName();QHostInfo hostInfo = QHostInfo::fromName(hostName);ui->plainTextEdit->appendPlainText("本机名称:" + hostName);QString locaIp;QList<QHostAddress> list = hostInfo.addresses();if (list.empty())return "null QString";foreach (QHostAddress addr, list) {if (addr.protocol() == QAbstractSocket::IPv4Protocol) {locaIp = addr.toString();break;}}return locaIp;
}void MainTcpServer::closeEvent(QCloseEvent *event)   //关闭窗口时候停止监听
{if (m_tcpServer->isListening())m_tcpServer->close();event->accept();
}void MainTcpServer::on_actStart_triggered()
{QString Ip = ui->comboBox->currentText();quint16 port = ui->spinBox->value();QHostAddress addr(Ip);m_tcpServer->listen(addr, port);  //监听指定的 IP 和指定的 portui->plainTextEdit->appendPlainText("服务器地址为:" + m_tcpServer->serverAddress().toString() + "   服务器端口:" + QString::number(m_tcpServer->serverPort()));ui->plainTextEdit->appendPlainText("开始监听...");ui->actStart->setEnabled(false);ui->actStop->setEnabled(true);m_labListen->setText("监听状态:正在监听...");
}void MainTcpServer::on_actStop_triggered()
{if (!m_tcpServer->isListening())return;m_tcpServer->close();  //停止监听ui->actStart->setEnabled(true);ui->actStop->setEnabled(false);m_labListen->setText("监听状态:监听已经停止");
}void MainTcpServer::on_actClear_triggered()
{ui->plainTextEdit->clear();
}void MainTcpServer::on_actQuit_triggered()
{close();
}void MainTcpServer::on_btnSend_clicked()
{QString msg = ui->lineEdit->text();ui->plainTextEdit->appendPlainText("[服务器:]" + msg);ui->lineEdit->clear();ui->plainTextEdit->hasFocus();QByteArray str = msg.toUtf8();str.append('\n');m_tcpSocket->write(str);
}void MainTcpServer::onSocketReadyRead()     //读取缓冲区行文本
{while (m_tcpSocket->canReadLine()) {ui->plainTextEdit->appendPlainText("[客户端:]" + m_tcpSocket->readLine());}
}void MainTcpServer::onClientConnected()    //客户端连接时
{ui->plainTextEdit->appendPlainText("客户端套接字连接\n对等(peer)地址:" + m_tcpSocket->peerAddress().toString()+ "    对等(peer)端口:" +  QString::number(m_tcpSocket->peerPort()));}void MainTcpServer::onClientDisonnected()  //客户端断开连接时
{ui->plainTextEdit->appendPlainText("客户端套接字断开");m_tcpSocket->deleteLater();
}void MainTcpServer::onNewConnection()
{m_tcpSocket = m_tcpServer->nextPendingConnection();   //创建 socketconnect(m_tcpSocket, SIGNAL(connected()), this, SLOT(onClientConnected()));connect(m_tcpSocket, SIGNAL(disconnected()), this, SLOT(onClientDisonnected()));connect(m_tcpSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(onSocketStateChange(QAbstractSocket::SocketState)));onSocketStateChange(m_tcpSocket->state());connect(m_tcpSocket, SIGNAL(readyRead()), this, SLOT(onSocketReadyRead()));
}void MainTcpServer::onSocketStateChange(QAbstractSocket::SocketState socketState)
{switch (socketState) {case QAbstractSocket::UnconnectedState:m_labSocket->setText("socket状态:UnconnectedState");break;case QAbstractSocket::HostLookupState:m_labSocket->setText("socket状态:HostLookupState");break;case QAbstractSocket::ConnectingState:m_labSocket->setText("socket状态:ConnectingState");break;case QAbstractSocket::ConnectedState:m_labSocket->setText("socket状态:ConnectedState");break;case QAbstractSocket::BoundState:m_labSocket->setText("socket状态:BoundState");break;case QAbstractSocket::ClosingState:m_labSocket->setText("socket状态:ClosingState");break;case QAbstractSocket::ListeningState:m_labSocket->setText("socket状态:ListeningState");break;default:m_labSocket->setText("socket状态:其他未知状态...");break;}
}

ui 文件实现

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0"><class>ExTcpServer</class><widget class="QMainWindow" name="ExTcpServer"><property name="geometry"><rect><x>0</x><y>0</y><width>573</width><height>341</height></rect></property><property name="windowTitle"><string>ExTcpServer</string></property><widget class="QWidget" name="centralWidget"><layout class="QVBoxLayout" name="verticalLayout"><item><layout class="QHBoxLayout" name="horizontalLayout"><item><spacer name="horizontalSpacer"><property name="orientation"><enum>Qt::Horizontal</enum></property><property name="sizeHint" stdset="0"><size><width>40</width><height>20</height></size></property></spacer></item><item><widget class="QLabel" name="labIP"><property name="text"><string>监听地址:</string></property><property name="alignment"><set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set></property></widget></item><item><widget class="QComboBox" name="comboBox"><property name="editable"><bool>true</bool></property><property name="currentText"><string>127.0.0.1</string></property></widget></item><item><widget class="QLabel" name="labPort"><property name="text"><string>端口:</string></property><property name="alignment"><set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set></property></widget></item><item><widget class="QSpinBox" name="spinBox"><property name="maximum"><number>65000</number></property><property name="value"><number>10000</number></property></widget></item></layout></item><item><widget class="QPlainTextEdit" name="plainTextEdit"/></item><item><layout class="QHBoxLayout" name="horizontalLayout_2"><item><widget class="QLineEdit" name="lineEdit"/></item><item><widget class="QPushButton" name="btnSend"><property name="text"><string>发送</string></property></widget></item></layout></item></layout></widget><widget class="QMenuBar" name="menuBar"><property name="geometry"><rect><x>0</x><y>0</y><width>573</width><height>25</height></rect></property></widget><widget class="QToolBar" name="mainToolBar"><property name="toolButtonStyle"><enum>Qt::ToolButtonFollowStyle</enum></property><attribute name="toolBarArea"><enum>TopToolBarArea</enum></attribute><attribute name="toolBarBreak"><bool>false</bool></attribute><addaction name="actStart"/><addaction name="actStop"/><addaction name="actClear"/><addaction name="actQuit"/><addaction name="separator"/></widget><widget class="QStatusBar" name="statusBar"/><action name="actStart"><property name="text"><string>开始监听</string></property><property name="toolTip"><string>开始监听</string></property></action><action name="actStop"><property name="text"><string>停止监听</string></property><property name="toolTip"><string>停止监听</string></property></action><action name="actClear"><property name="text"><string>清除</string></property><property name="toolTip"><string>清除文本</string></property></action><action name="actQuit"><property name="text"><string>退出</string></property><property name="toolTip"><string>退出程序</string></property></action></widget><layoutdefault spacing="6" margin="11"/><resources/><connections/>
</ui>

实现界面如下:

实现部分–客户端

头文件实现

#ifndef TCPCLIENT_H
#define TCPCLIENT_H#include <QMainWindow>
#include <QLabel>
#include <QTcpSocket>
#include <QHostInfo>namespace Ui {class TcpClient;
}class TcpClient : public QMainWindow
{Q_OBJECTpublic:explicit TcpClient(QWidget *parent = nullptr);~TcpClient();private:QString getLocalIp();                  //获取本本机 IPprotected:void closeEvent(QCloseEvent *event);private slots://UI 定义的槽函数void on_actConnect_triggered();     //请求连接到服务器void on_actDisconnect_triggered();  //断开与服务器的连接void on_actClear_triggered();       //清除内容void on_actQuit_triggered();        //退出程序void on_btnSend_clicked();          //发送文本消息//自定义的槽函数void onConnected();void onDisconnected();void onSocketReadyRead();           //从socket读取传入的数据void onSocketStateChange(QAbstractSocket::SocketState socketState);private:Ui::TcpClient *ui;QLabel* m_labSocket;QTcpSocket* m_tcpSocket;
};#endif // TCPCLIENT_H

cpp 文件实现


#include "TcpClient.h"
#include "ui_TcpClient.h"TcpClient::TcpClient(QWidget *parent) :QMainWindow(parent),ui(new Ui::TcpClient)
{ui->setupUi(this);m_labSocket = new QLabel("socket状态:");m_labSocket->setMidLineWidth(150);ui->statusBar->addWidget(m_labSocket);m_tcpSocket = new QTcpSocket(this);QString localIp = getLocalIp();this->setWindowTitle(windowTitle() + "----本机IP:" + localIp);ui->comboBox->addItem(localIp);connect(m_tcpSocket, SIGNAL(connected()), this, SLOT(onConnected()));connect(m_tcpSocket, SIGNAL(disconnected()), this, SLOT(onDisconnected()));connect(m_tcpSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(onSocketStateChange(QAbstractSocket::SocketState)));connect(m_tcpSocket, SIGNAL(readyRead()), this, SLOT(onSocketReadyRead()));
}TcpClient::~TcpClient()
{delete ui;
}QString TcpClient::getLocalIp()
{QString hostName = QHostInfo::localHostName();QHostInfo hostInfo = QHostInfo::fromName(hostName);ui->plainTextEdit->appendPlainText("本机名称:" + hostName);QString localIp;foreach (QHostAddress addr, hostInfo.addresses()) {if (QAbstractSocket::IPv4Protocol == addr.protocol()) {localIp = addr.toString();break;}}return localIp;
}void TcpClient::closeEvent(QCloseEvent *event)
{if (m_tcpSocket->state() == QAbstractSocket::ConnectedState)m_tcpSocket->disconnectFromHost();event->accept();
}void TcpClient::onConnected()
{ui->plainTextEdit->appendPlainText("已经连接到服务器\n客户端套接字连接\n对等(peer)地址:" + m_tcpSocket->peerAddress().toString()+ "    对等(peer)端口:" +  QString::number(m_tcpSocket->peerPort()));ui->actConnect->setEnabled(false);ui->actDisconnect->setEnabled(true);
}void TcpClient::onDisconnected()
{ui->plainTextEdit->appendPlainText("已经断开与服务器的连接\n");ui->actConnect->setEnabled(true);ui->actDisconnect->setEnabled(false);
}void TcpClient::onSocketReadyRead()
{while (m_tcpSocket->canReadLine()) {ui->plainTextEdit->appendPlainText("[服务器:]" + m_tcpSocket->readLine());}
}void TcpClient::onSocketStateChange(QAbstractSocket::SocketState socketState)
{switch (socketState) {case QAbstractSocket::UnconnectedState:m_labSocket->setText("socket状态:UnconnectedState");break;case QAbstractSocket::HostLookupState:m_labSocket->setText("socket状态:HostLookupState");break;case QAbstractSocket::ConnectingState:m_labSocket->setText("socket状态:ConnectingState");break;case QAbstractSocket::ConnectedState:m_labSocket->setText("socket状态:ConnectedState");break;case QAbstractSocket::BoundState:m_labSocket->setText("socket状态:BoundState");break;case QAbstractSocket::ClosingState:m_labSocket->setText("socket状态:ClosingState");break;case QAbstractSocket::ListeningState:m_labSocket->setText("socket状态:ListeningState");break;default:m_labSocket->setText("socket状态:其他未知状态...");break;}
}void TcpClient::on_actConnect_triggered()
{QString addr = ui->comboBox->currentText();quint16 port = ui->spinBox->value();m_tcpSocket->connectToHost(addr, port);
}void TcpClient::on_actDisconnect_triggered()
{if(m_tcpSocket->state() == QAbstractSocket::ConnectedState)m_tcpSocket->disconnectFromHost();
}void TcpClient::on_actClear_triggered()
{ui->plainTextEdit->clear();
}void TcpClient::on_actQuit_triggered()
{close();
}void TcpClient::on_btnSend_clicked()
{QString msg = ui->lineEdit->text();ui->plainTextEdit->appendPlainText("[客户端:]" + msg);ui->lineEdit->clear();ui->lineEdit->setFocus();QByteArray str = msg.toUtf8();str.append('\n');m_tcpSocket->write(str);
}

ui 设计文件

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0"><class>ExTcpClient</class><widget class="QMainWindow" name="ExTcpClient"><property name="geometry"><rect><x>0</x><y>0</y><width>561</width><height>353</height></rect></property><property name="windowTitle"><string>ExTcpClient</string></property><widget class="QWidget" name="centralWidget"><layout class="QVBoxLayout" name="verticalLayout"><item><layout class="QHBoxLayout" name="horizontalLayout"><item><spacer name="horizontalSpacer"><property name="orientation"><enum>Qt::Horizontal</enum></property><property name="sizeHint" stdset="0"><size><width>40</width><height>20</height></size></property></spacer></item><item><widget class="QLabel" name="labIP"><property name="text"><string>服务器地址:</string></property><property name="alignment"><set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set></property></widget></item><item><widget class="QComboBox" name="comboBox"><property name="editable"><bool>true</bool></property><property name="currentText"><string>127.0.0.1</string></property></widget></item><item><widget class="QLabel" name="labPort"><property name="text"><string>端口:</string></property><property name="alignment"><set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set></property></widget></item><item><widget class="QSpinBox" name="spinBox"><property name="maximum"><number>65000</number></property><property name="value"><number>10000</number></property></widget></item></layout></item><item><widget class="QPlainTextEdit" name="plainTextEdit"/></item><item><layout class="QHBoxLayout" name="horizontalLayout_2"><item><widget class="QLineEdit" name="lineEdit"/></item><item><widget class="QPushButton" name="btnSend"><property name="text"><string>发送</string></property></widget></item></layout></item></layout></widget><widget class="QMenuBar" name="menuBar"><property name="geometry"><rect><x>0</x><y>0</y><width>561</width><height>25</height></rect></property></widget><widget class="QToolBar" name="mainToolBar"><attribute name="toolBarArea"><enum>TopToolBarArea</enum></attribute><attribute name="toolBarBreak"><bool>false</bool></attribute><addaction name="actConnect"/><addaction name="actDisconnect"/><addaction name="actClear"/><addaction name="actQuit"/></widget><widget class="QStatusBar" name="statusBar"/><action name="actConnect"><property name="text"><string>请求连接</string></property><property name="toolTip"><string>请求连接到服务器</string></property></action><action name="actDisconnect"><property name="text"><string>断开连接</string></property><property name="toolTip"><string>断开与服务器的连接</string></property></action><action name="actClear"><property name="text"><string>清空</string></property><property name="toolTip"><string>清空编辑框文本</string></property></action><action name="actQuit"><property name="text"><string>退出</string></property><property name="toolTip"><string>退出程序</string></property></action></widget><layoutdefault spacing="6" margin="11"/><resources/><connections/>
</ui>

ui界面如下:

TCP通信之QTcpServer和QTcpSocket,服务器和客户端通讯相关推荐

  1. Java如何实现不同局域网TCP通信+群聊(云服务器实现)

    最近在CSDN上学习了Socket通信群聊的方法,就觉得这样就可以实现QQ的样子了.然后让女朋友用电脑试了一下,运行用户端代码,发现连连接到服务器都做不到.后来经过自己的研究,实现了QQ群聊的功能,后 ...

  2. 科佩克机器人TCP通信(机器人控制器作为服务器)

    文章目录 一.修改机器人控制端的IP地址 1. 依次点击**系统,权限管理**,在用户登录界面输入密码: 2. 同时按**上档,联锁,清除**:界面切换如图所示, 3. 在左下角划出start控件,选 ...

  3. C# TCP通信发送桌面图片到服务器

    第一次发文,也是啥也不会,初次接触C#,觉得网络通信挺好玩,就在网上找例子看,有很多例子和方法都可以实现传送图片,同步或异步,通过套接字或者简单的客户端等等都可以通过Networkstream流实现数 ...

  4. Java网络编程 - TCP通信

    文章目录 TCP通信 快速入门(一发一收) 编写客户端代码 编写服务器代码 多发多收 多发多收(同时接受多个客户端) 线程池优化 TCP通信 快速入门(一发一收) TCP协议回顾: TCP是一种面向连 ...

  5. Socket编程(简单(C++)实现TCP通信)

    一.什么是socket? socket顾名思义就是套接字的意思,用于描述地址和端口,是一个通信链的句柄.应用程序通过socket向网络发出请求或者回应. socket编程有三种,流式套接字(SOCK_ ...

  6. 糖儿飞教你学C++ Socket网络编程——6.控制台版的TCP通信程序

    根据图2-1的TCP通信程序的流程,下面编程实现一个控制台版的TCP通信程序,程序分为服务器端和客户端,双方可以相互发送消息,运行效果如图2-4所示. 图2-4 控制台版的TCP通信程序(左图为服务器 ...

  7. 易语言和python混合编程_[我叫以赏]Python制作交互式的服务器与客户端互相通讯(引用SOCKET模块)...

    前言 欢迎来到我的教程啊,我是以赏,这么说吧,Python我也在学习并未达到"精通"的地步,一部分呢是自学,一部分是老师"传授"的.但我认为学习Python应该 ...

  8. 专业课程设计之客户与服务器程序的同步与通信机制的设计(二)TCP通信

    源码下载地址为: http://download.csdn.net/detail/qq78442761/9856423 ---------------------------------------- ...

  9. QT网络编程——TCP服务器和客户端通信

    目录 一.服务器端 1.QT中TCP服务器的开发思路 2.QT服务器界面设计 3.QT服务器代码实现 二.客户端 1.QT中TCP客户端的开发思路 2.QT客户端界面设计 3.QT客户端代码实现 网络 ...

最新文章

  1. 金蝶K3cloud问题单排查
  2. highcharts总结
  3. Java程序设计4——集合类
  4. 《C++ Primer第五版》习题答案
  5. 从分库分表到Database Plus,重新认知ShardingSphere
  6. 前端学java还是python_零基础应该选择学习 java、php、前端 还是 python?
  7. Kubernetes 小白学习笔记(17)--集群安全-APIServer的安全模型
  8. @async 报错_async异步操作函数
  9. 网页中返回顶部代码及注释说明
  10. 江西银行服务器怎么选择硬件配置
  11. linux安装ipk游戏,添加软件包 IPK
  12. 【推荐】推荐一款云盘 不限速 【下载免登录】【下载不限速】【2T大存储】
  13. 区块链在网络安全中有何作用?
  14. 机器学习(二)线性回归、多项式回归、多元回归
  15. 利用Javascript prototype特性使用模板设计模式对浏览器端绘图功能进行设计
  16. SSD的使用寿命一般有多久
  17. 《炬丰科技-半导体工艺》清洗含有介电膜的半导体晶片的方法
  18. 普通内存、ECC内存和REG ECC内存有什么不同?
  19. python、C++、机器学习、深度学习-------资源、代码练习的常用网站大全
  20. 基于SSM的宠物动物猫狗商城【数据库设计、源码、开题报告】

热门文章

  1. Reactor模式是什么_晏无心_新浪博客
  2. Unity优化之减少Drawcall
  3. 【面经】2022互联网算法岗面试总结
  4. azure linux 多磁盘 lvm,问题:LVM lvextend增加空间后,df查看还是原来空间
  5. [源码和文档分享]基于QT实现的怪怪水族馆益智游戏
  6. 智慧节能管理系统的优点
  7. 服务器维护后黑莲花刷新,魔兽世界怀旧服黑莲花刷新机制_wow怀旧服黑莲花刷新地点_3DM网游...
  8. java笔试面试题整理
  9. 配置 nginx 解析 php
  10. ctrip android view,携程旅行-订酒店机票火车票