前言
網(wǎng)絡通信是程序員必須會的一項生存技能,這里簡單的實現(xiàn)了服務端和客戶端通信的兩個小示例,代碼可以直接拿來用,開發(fā)環(huán)境是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 {
class TCPServer;
}
class TCPServer : public QWidget
{
Q_OBJECT
public:
explicit TCPServer(QWidget *parent = nullptr);
~TCPServer();
void initNetwork(QString ip,quint16 port);
void stopNetwork();
private slots:
void onNewConnection();//QTcpServer的newConnection()信號
void onConnected(); //可以不添加該接口
void onDisconnected(); //可以不添加該接口
void onSocketReadyRead();//讀取socket傳入的數(shù)據(jù)
void on_pushButton_clicked();
private:
Ui::TCPServer *ui;
QTcpServer *tcpServer; //TCP服務器
QTcpSocket *tcpSocket;//TCP通訊的Socket
QString getLocalIP();//獲取本機IP地址
void closeEvent(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地址和監(jiān)聽的端口號
}
TCPServer::~TCPServer()
{
delete ui;
}
void TCPServer::initNetwork(QString ip, quint16 port)
{
tcpServer=new QTcpServer(this);
connect(tcpServer,SIGNAL(newConnection()),this,SLOT(onNewConnection()));
QHostAddress addr(ip);
tcpServer->listen(addr,port);
}
void TCPServer::stopNetwork()
{
if(tcpServer->isListening()){//tcpServer正在監(jiān)聽
tcpServer->close();;//停止網(wǎng)絡監(jiān)聽
}
}
void TCPServer::onNewConnection()
{
tcpSocket = tcpServer->nextPendingConnection(); //創(chuàng)建socket
connect(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(); //根據(jù)條件篩選出本地IPV4地址
}
}
return ipString;
}
void TCPServer::closeEvent(QCloseEvent *event)
{
stopNetwork();
event->accept();
}
void TCPServer::on_pushButton_clicked()
{
QString msg = ui->lineEdit->text();
ui->lineEdit->setFocus();//光標回到lineEdit
if(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 {
class TCPClient;
}
class TCPClient : public QWidget
{
Q_OBJECT
public:
explicit TCPClient(QWidget *parent = nullptr);
~TCPClient();
void initNetwork(QString ip,quint16 port);
void stopNetwork();
private slots:
//自定義槽函數(shù)
void onConnected(); //可以不添加該接口
void onDisconnected(); //可以不添加該接口
void onSocketReadyRead();//讀取socket傳入的數(shù)據(jù)
void on_pushButton_clicked();
private:
Ui::TCPClient *ui;
QTcpSocket *tcpClient; //socket
QString getLocalIP();//獲取本機IP地址
void closeEvent(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=new QTcpSocket(this); //創(chuàng)建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(); //根據(jù)條件篩選出本地IPV4地址
}
}
return ipString;
}
void TCPClient::closeEvent(QCloseEvent *event)
{
stopNetwork();
event->accept();
}
void TCPClient::on_pushButton_clicked()
{
//發(fā)送數(shù)據(jù)
QString msg=ui->lineEdit->text();
ui->lineEdit->setFocus();//光標回到lineEdit
if(msg.isEmpty())return;
ui->lineEdit->clear();
ui->plainTextEdit->appendPlainText("[客戶端] "+msg);
QByteArray str=msg.toUtf8();
str.append('\n');
tcpClient->write(str);
}
4.測試效果
文章來源:http://www.zghlxwxcb.cn/news/detail-522947.html
總結
好了,兩個小程序寫完并可以運行進行通信,簡單的實現(xiàn),原理后序會專門寫篇文章,這里可以直接照著上述寫就OK啦,886!文章來源地址http://www.zghlxwxcb.cn/news/detail-522947.html
到了這里,關于【Qt專欄】Qt實現(xiàn)TCP服務端和客戶端通信的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!