本文主要是介绍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协议工作原理及实战的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!