文章目录
前言
网络通信是程序员必须会的一项生存技能,这里简单的实现了服务端和客户端通信的两个小示例,代码可以直接拿来用,开发环境是Qt5.9.6。
一、TCP服务端
1.项目架构
2.tcpserver.h文件
#ifndef TCPSERVER_H#define TCPSERVER_H#include<QWidget>//添加下面三个头文件,记得在pro文件里添加 network 模块#include<QTcpServer>#include<QTcpSocket>#include<QtNetwork>namespace Ui {classTCPServer;}classTCPServer:public QWidget
{
Q_OBJECT
public:explicitTCPServer(QWidget *parent =nullptr);~TCPServer();voidinitNetwork(QString ip,quint16 port);voidstopNetwork();private slots:voidonNewConnection();//QTcpServer的newConnection()信号voidonConnected();//可以不添加该接口voidonDisconnected();//可以不添加该接口voidonSocketReadyRead();//读取socket传入的数据voidon_pushButton_clicked();private:
Ui::TCPServer *ui;
QTcpServer *tcpServer;//TCP服务器
QTcpSocket *tcpSocket;//TCP通讯的Socket
QString getLocalIP();//获取本机IP地址voidcloseEvent(QCloseEvent *event);};#endif// TCPSERVER_H
3.tcpserver.cpp文件
#include"tcpserver.h"#include"ui_tcpserver.h"
TCPServer::TCPServer(QWidget *parent):QWidget(parent),ui(new Ui::TCPServer){
ui->setupUi(this);initNetwork(getLocalIP(),55555);//指定ip地址和监听的端口号}
TCPServer::~TCPServer(){delete ui;}void TCPServer::initNetwork(QString ip, quint16 port){
tcpServer=newQTcpServer(this);connect(tcpServer,SIGNAL(newConnection()),this,SLOT(onNewConnection()));
QHostAddress addr(ip);
tcpServer->listen(addr,port);}void TCPServer::stopNetwork(){if(tcpServer->isListening()){//tcpServer正在监听
tcpServer->close();;//停止网络监听}}void TCPServer::onNewConnection(){
tcpSocket = tcpServer->nextPendingConnection();//创建socketconnect(tcpSocket,SIGNAL(readyRead()),this,SLOT(onSocketReadyRead()));connect(tcpSocket,SIGNAL(connected()),this,SLOT(onConnected()));onConnected();connect(tcpSocket,SIGNAL(disconnected()),this,SLOT(onDisconnected()));}void TCPServer::onConnected(){
ui->plainTextEdit->appendPlainText(QStringLiteral("***客户端连接 ")+QStringLiteral("ip地址:")+tcpSocket->peerAddress().toString()+QStringLiteral(" 端口号:")+QString::number(tcpSocket->peerPort())+"***");}void TCPServer::onDisconnected(){
ui->plainTextEdit->appendPlainText(QStringLiteral("***客户端断开连接***"));}void TCPServer::onSocketReadyRead(){while(tcpSocket->canReadLine()){
QByteArray msg = tcpSocket->readLine();
ui->plainTextEdit->appendPlainText("[客户端] "+msg);}}
QString TCPServer::getLocalIP(){
QString ipString = Q_NULLPTR;
QHostInfo hostInfo = QHostInfo::fromName(QHostInfo::localHostName());//从本地主机名称获取主机信息
QList<QHostAddress> listAddr = hostInfo.addresses();//本地主机ip地址列表(IPV4/IPV6)
foreach (auto addr, listAddr){if((addr.isNull()==false)&&(addr.protocol()== QAbstractSocket::IPv4Protocol)&&(addr != QHostAddress::LocalHost)){
ipString = addr.toString();//根据条件筛选出本地IPV4地址}}return ipString;}void TCPServer::closeEvent(QCloseEvent *event){stopNetwork();
event->accept();}void TCPServer::on_pushButton_clicked(){
QString msg = ui->lineEdit->text();
ui->lineEdit->setFocus();//光标回到lineEditif(msg.isEmpty())return;
ui->lineEdit->clear();
ui->plainTextEdit->appendPlainText("[服务端] "+msg);
QByteArray str = msg.toUtf8();
str.append("\n");
tcpSocket->write(str);}
4.测试效果
二、TCP客户端
1.项目架构
2.tcpserver.h文件
#ifndef TCPCLIENT_H#define TCPCLIENT_H#include<QWidget>//添加下面两个头文件,记得在pro文件里添加 network 模块#include<QTcpSocket>#include<QtNetwork>namespace Ui {classTCPClient;}classTCPClient:public QWidget
{
Q_OBJECT
public:explicitTCPClient(QWidget *parent =nullptr);~TCPClient();voidinitNetwork(QString ip,quint16 port);voidstopNetwork();private slots://自定义槽函数voidonConnected();//可以不添加该接口voidonDisconnected();//可以不添加该接口voidonSocketReadyRead();//读取socket传入的数据voidon_pushButton_clicked();private:
Ui::TCPClient *ui;
QTcpSocket *tcpClient;//socket
QString getLocalIP();//获取本机IP地址voidcloseEvent(QCloseEvent *event);};#endif// TCPCLIENT_H
3.tcpserver.cpp文件
#include"tcpclient.h"#include"ui_tcpclient.h"
TCPClient::TCPClient(QWidget *parent):QWidget(parent),ui(new Ui::TCPClient){
ui->setupUi(this);initNetwork(getLocalIP(),55555);//指定服务端ip地址和的端口号}
TCPClient::~TCPClient(){delete ui;}void TCPClient::initNetwork(QString ip, quint16 port){
tcpClient=newQTcpSocket(this);//创建socket变量connect(tcpClient,SIGNAL(connected()),this,SLOT(onConnected()));connect(tcpClient,SIGNAL(disconnected()),this,SLOT(onDisconnected()));connect(tcpClient,SIGNAL(readyRead()),this,SLOT(onSocketReadyRead()));
tcpClient->connectToHost(ip,port);}void TCPClient::stopNetwork(){//断开与服务器的连接if(tcpClient->state()==QAbstractSocket::ConnectedState){
tcpClient->disconnectFromHost();}}void TCPClient::onConnected(){
ui->plainTextEdit->appendPlainText("***已连接到服务器***");}void TCPClient::onDisconnected(){
ui->plainTextEdit->appendPlainText("***已断开与服务器的连接***");}void TCPClient::onSocketReadyRead(){while(tcpClient->canReadLine()){
QByteArray msg = tcpClient->readLine();
ui->plainTextEdit->appendPlainText("[服务端] "+msg);}}
QString TCPClient::getLocalIP(){
QString ipString = Q_NULLPTR;
QHostInfo hostInfo = QHostInfo::fromName(QHostInfo::localHostName());//从本地主机名称获取主机信息
QList<QHostAddress> listAddr = hostInfo.addresses();//本地主机ip地址列表(IPV4/IPV6)
foreach (auto addr, listAddr){if((addr.isNull()==false)&&(addr.protocol()== QAbstractSocket::IPv4Protocol)&&(addr != QHostAddress::LocalHost)){
ipString = addr.toString();//根据条件筛选出本地IPV4地址}}return ipString;}void TCPClient::closeEvent(QCloseEvent *event){stopNetwork();
event->accept();}void TCPClient::on_pushButton_clicked(){//发送数据
QString msg=ui->lineEdit->text();
ui->lineEdit->setFocus();//光标回到lineEditif(msg.isEmpty())return;
ui->lineEdit->clear();
ui->plainTextEdit->appendPlainText("[客户端] "+msg);
QByteArray str=msg.toUtf8();
str.append('\n');
tcpClient->write(str);}
4.测试效果
总结
好了,两个小程序写完并可以运行进行通信,简单的实现,原理后序会专门写篇文章,这里可以直接照着上述写就OK啦,886!
本文转载自: https://blog.csdn.net/weixin_43729127/article/details/126914710
版权归原作者 拉伊卜 所有, 如有侵权,请联系我们删除。
版权归原作者 拉伊卜 所有, 如有侵权,请联系我们删除。