71-TCP协议工作原理及实战

2024-06-18 14:12
文章标签 实战 工作 协议 原理 tcp 71

本文主要是介绍71-TCP协议工作原理及实战,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一 服务器端

#ifndef MAINWINDOW_H
#define MAINWINDOW_H#include <QMainWindow>
#include <QTcpServer> // 专门用于建立TCP连接并传输数据信息
#include <QtNetwork> // 此模块提供开发TCP/IP客户端和服务器的类QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACEclass MainWindow : public QMainWindow
{Q_OBJECTpublic:MainWindow(QWidget *parent = nullptr);~MainWindow();private:Ui::MainWindow *ui;// 自定义如下
private:QTcpServer *tcpserver; //TCP服务器QTcpSocket *tcpsocket;// TCP通讯socketQString GetLocalIpAddress(); // 获取本机的IP地址private slots:void clientconnect();void clientdisconnect();void socketreaddata();void newconnection();void on_pushButton_Start_clicked();void on_pushButton_Stop_clicked();void on_pushButton_Send_clicked();
protected:void closeEvent(QCloseEvent *event);
};
#endif // MAINWINDOW_H***************************************************************
***************************************************************
mainwindow.cpp#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>MainWindow::MainWindow(QWidget *parent): QMainWindow(parent), ui(new Ui::MainWindow)
{ui->setupUi(this);//测试是否获取本地地址QString strip = GetLocalIpAddress();QMessageBox::information(this,"数据",strip,QMessageBox::Yes);//添加到comboxip里面ui->comboBoxIp->addItem(strip);//调用监听tcpserver = new QTcpServer(this);connect(tcpserver,SIGNAL(newConnection()),this,SLOT(newconnection()));}MainWindow::~MainWindow()
{delete ui;
}
// 获取本机的IP地址
QString MainWindow::GetLocalIpAddress()
{QString hostname=QHostInfo::localHostName();QHostInfo hostinfo=QHostInfo::fromName(hostname);QString localip="";QList<QHostAddress> addresslist=hostinfo.addresses();if(!addresslist.isEmpty()){for (int i=0;i<addresslist.count();i++){QHostAddress addrhost=addresslist.at(i);if(QAbstractSocket::IPv4Protocol==addrhost.protocol()){localip=addrhost.toString();break;}}}return localip;
}void MainWindow::clientconnect()
{//客户端连接ui->plainTextEdit_DispMsg->appendPlainText("****客户端套接字socket连接****");ui->plainTextEdit_DispMsg->appendPlainText("**********peer address:"+tcpsocket->peerAddress().toString());ui->plainTextEdit_DispMsg->appendPlainText("**********peer port:"+QString::number(tcpsocket->peerPort()));}void MainWindow::clientdisconnect()
{//客户端断开连接ui->plainTextEdit_DispMsg->appendPlainText("**********客户端socket断开连接**********");tcpsocket->deleteLater();
}void MainWindow::socketreaddata()
{//读取数据while(tcpsocket->canReadLine()){ui->plainTextEdit_DispMsg->appendPlainText("[in]"+tcpsocket->readLine());}}//新建连接
void MainWindow::newconnection()
{//连接tcpsocket = tcpserver->nextPendingConnection();connect(tcpsocket,SIGNAL(connect()),this,SLOT(clientconnect()));clientconnect();//断开连接connect(tcpsocket,SIGNAL(disconnect()),this,SLOT(clientdisconnect()));//读数据connect(tcpsocket,SIGNAL(readyRead()),this,SLOT(socketreaddata()));//状态connect(tcpsocket,SIGNAL(stateChanged(QAbstractSocket::SocketState)),this,SLOT(OnSocketStateChanged(QAbstractSocket::SocketState)));
}//启动服务
void MainWindow::on_pushButton_Start_clicked()
{//开始监听QString ip = ui->comboBoxIp->currentText();qint16 port = ui->spinBoxPort->value();QHostAddress address(ip);tcpserver->listen(address,port);ui->plainTextEdit_DispMsg->appendPlainText("$$$$$开始监听$$$$$$");ui->plainTextEdit_DispMsg->appendPlainText("$$$$$$$$$$服务器地址$$$$$$$$$$:"+tcpserver->serverAddress().toString());ui->plainTextEdit_DispMsg->appendPlainText("$$$$$$$$$$服务器端口$$$$$$$$$$:"+QString::number(tcpserver->serverPort()));ui->pushButton_Start->setEnabled(false);ui->pushButton_Stop->setEnabled(true);}void MainWindow::on_pushButton_Stop_clicked()
{if(tcpserver->isListening()){tcpserver->close();ui->pushButton_Start->setEnabled(true);ui->pushButton_Stop->setEnabled(false);}
}void MainWindow::on_pushButton_Send_clicked()
{QString strmsg = ui->lineEdit_InputMsg->text();ui->plainTextEdit_DispMsg->appendPlainText("[out]"+strmsg);ui->lineEdit_InputMsg->clear();QByteArray str = strmsg.toUtf8();str.append("\n");tcpsocket->write(str);}void MainWindow::closeEvent(QCloseEvent *event)
{if(tcpserver->isListening()){tcpserver->close();}event->accept();
}*********************************************************

二 客户端

#ifndef MAINWINDOW_H
#define MAINWINDOW_H#include <QMainWindow>
#include <QTcpSocket> // 专门用于建立TCP连接并传输数据信息
#include <QHostAddress>
#include <QHostInfo>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACEclass MainWindow : public QMainWindow
{Q_OBJECTpublic:MainWindow(QWidget *parent = nullptr);~MainWindow();private:Ui::MainWindow *ui;
private:QTcpSocket *tcpclient;//客户端tcp套接字QString getlocalip();//获取本机ip地址
protected:void closeEvent(QCloseEvent *event);
private slots:void clientfunc();void disclientfunc();void socketreaddata();void on_pushButton_Connect_clicked();void on_pushButton_Disconnect_clicked();void on_pushButton_Send_clicked();
};
#endif // MAINWINDOW_H**********************************************************
.c#include "mainwindow.h"
#include "ui_mainwindow.h"MainWindow::MainWindow(QWidget *parent): QMainWindow(parent), ui(new Ui::MainWindow)
{ui->setupUi(this);tcpclient = new QTcpSocket(this);QString strip = getlocalip();ui->comboBoxIp->addItem(strip);connect(tcpclient,SIGNAL(connected()),this,SLOT(clientfunc()));connect(tcpclient,SIGNAL(disconnected()),this,SLOT(disclientfunc()));connect(tcpclient,SIGNAL(readyRead()),this,SLOT(socketreaddata()));}MainWindow::~MainWindow()
{delete ui;
}
//获取本机ip
QString MainWindow::getlocalip()
{QString hostname = QHostInfo::localHostName();QHostInfo hostinfo = QHostInfo::fromName(hostname);QString localip = "";QList<QHostAddress> addlist = hostinfo.addresses();if(!addlist.isEmpty()){for(int i = 0;i < addlist.count();i++){QHostAddress ahost = addlist.at(i);if(QAbstractSocket::IPv4Protocol==ahost.protocol()){localip = ahost.toString();break;}}}return localip;
}void MainWindow::closeEvent(QCloseEvent *event)
{if(tcpclient->state()==QAbstractSocket::ConnectedState){tcpclient->disconnectFromHost();}event->accept();
}
void MainWindow::clientfunc()
{ui->plainTextEdit_DispMsg->appendPlainText("**已经连接到服务器端");ui->plainTextEdit_DispMsg->appendPlainText("**peer address:"+tcpclient->peerAddress().toString());ui->plainTextEdit_DispMsg->appendPlainText("**peer port:"+QString::number(tcpclient->peerPort()));ui->pushButton_Connect->setEnabled(false);ui->pushButton_Disconnect->setEnabled(true);}void MainWindow::disclientfunc()
{ui->plainTextEdit_DispMsg->appendPlainText("**已经断开与服务器的连接");ui->pushButton_Connect->setEnabled(true);ui->pushButton_Disconnect->setEnabled(false);}void MainWindow::socketreaddata()
{while(tcpclient->canReadLine()){ui->plainTextEdit_DispMsg->appendPlainText("[in]"+tcpclient->readLine());}
}void MainWindow::on_pushButton_Connect_clicked()
{QString addr = ui->comboBoxIp->currentText();qint16 port = ui->spinBoxPort->value();tcpclient->connectToHost(addr,port);
}void MainWindow::on_pushButton_Disconnect_clicked()
{if(tcpclient->state()==QAbstractSocket::ConnectedState){tcpclient->disconnectFromHost();}}void MainWindow::on_pushButton_Send_clicked()
{QString strmsg = ui->lineEdit_InputMsg->text();ui->plainTextEdit_DispMsg->appendPlainText("[out]:"+strmsg);ui->lineEdit_InputMsg->clear();QByteArray str = strmsg.toUtf8();str.append("\n");tcpclient->write(str);}

这篇关于71-TCP协议工作原理及实战的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1072215

相关文章

Java编译生成多个.class文件的原理和作用

《Java编译生成多个.class文件的原理和作用》作为一名经验丰富的开发者,在Java项目中执行编译后,可能会发现一个.java源文件有时会产生多个.class文件,从技术实现层面详细剖析这一现象... 目录一、内部类机制与.class文件生成成员内部类(常规内部类)局部内部类(方法内部类)匿名内部类二、

Spring Boot + MyBatis Plus 高效开发实战从入门到进阶优化(推荐)

《SpringBoot+MyBatisPlus高效开发实战从入门到进阶优化(推荐)》本文将详细介绍SpringBoot+MyBatisPlus的完整开发流程,并深入剖析分页查询、批量操作、动... 目录Spring Boot + MyBATis Plus 高效开发实战:从入门到进阶优化1. MyBatis

MyBatis 动态 SQL 优化之标签的实战与技巧(常见用法)

《MyBatis动态SQL优化之标签的实战与技巧(常见用法)》本文通过详细的示例和实际应用场景,介绍了如何有效利用这些标签来优化MyBatis配置,提升开发效率,确保SQL的高效执行和安全性,感... 目录动态SQL详解一、动态SQL的核心概念1.1 什么是动态SQL?1.2 动态SQL的优点1.3 动态S

Pandas使用SQLite3实战

《Pandas使用SQLite3实战》本文主要介绍了Pandas使用SQLite3实战,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学... 目录1 环境准备2 从 SQLite3VlfrWQzgt 读取数据到 DataFrame基础用法:读

Python中随机休眠技术原理与应用详解

《Python中随机休眠技术原理与应用详解》在编程中,让程序暂停执行特定时间是常见需求,当需要引入不确定性时,随机休眠就成为关键技巧,下面我们就来看看Python中随机休眠技术的具体实现与应用吧... 目录引言一、实现原理与基础方法1.1 核心函数解析1.2 基础实现模板1.3 整数版实现二、典型应用场景2

Java的IO模型、Netty原理解析

《Java的IO模型、Netty原理解析》Java的I/O是以流的方式进行数据输入输出的,Java的类库涉及很多领域的IO内容:标准的输入输出,文件的操作、网络上的数据传输流、字符串流、对象流等,这篇... 目录1.什么是IO2.同步与异步、阻塞与非阻塞3.三种IO模型BIO(blocking I/O)NI

Python实战之屏幕录制功能的实现

《Python实战之屏幕录制功能的实现》屏幕录制,即屏幕捕获,是指将计算机屏幕上的活动记录下来,生成视频文件,本文主要为大家介绍了如何使用Python实现这一功能,希望对大家有所帮助... 目录屏幕录制原理图像捕获音频捕获编码压缩输出保存完整的屏幕录制工具高级功能实时预览增加水印多平台支持屏幕录制原理屏幕

最新Spring Security实战教程之Spring Security安全框架指南

《最新SpringSecurity实战教程之SpringSecurity安全框架指南》SpringSecurity是Spring生态系统中的核心组件,提供认证、授权和防护机制,以保护应用免受各种安... 目录前言什么是Spring Security?同类框架对比Spring Security典型应用场景传统

最新Spring Security实战教程之表单登录定制到处理逻辑的深度改造(最新推荐)

《最新SpringSecurity实战教程之表单登录定制到处理逻辑的深度改造(最新推荐)》本章节介绍了如何通过SpringSecurity实现从配置自定义登录页面、表单登录处理逻辑的配置,并简单模拟... 目录前言改造准备开始登录页改造自定义用户名密码登陆成功失败跳转问题自定义登出前后端分离适配方案结语前言

OpenManus本地部署实战亲测有效完全免费(最新推荐)

《OpenManus本地部署实战亲测有效完全免费(最新推荐)》文章介绍了如何在本地部署OpenManus大语言模型,包括环境搭建、LLM编程接口配置和测试步骤,本文给大家讲解的非常详细,感兴趣的朋友一... 目录1.概况2.环境搭建2.1安装miniconda或者anaconda2.2 LLM编程接口配置2