首页 > 编程知识 正文

qt网络通信,qt tcp通信

时间:2023-05-06 02:28:40 阅读:140195 作者:418

它是本人在学习QT和计算机网络时自行开发的TCP网络通信软件,包括服务器端和客户端两个步骤,可供专业人员测试使用。 我自己也经常用它们进行网络测试,详细评论,欢迎参考。 也可以先放图,源代码附在下面,在这里直接下载。 https://download.csdn.net/download/quad

一、server端

(1).mainwindow.h

# ifndef main window _ h # define main window _ h # includeqmainwindow # includeqtcpserver # includeqtextcodec//为中文# includeq includeqmessagebox # includeqbytearray # include qimage//图# includeqtimer # includeqbuffer # include my thread. 类主窗口: publicqmainwindow { q _ object public : explicit主窗口(q构件* parent=0); ~主窗口(; QImage *image; QTimer *timer; //线程实验我的线程*线程; int pb; private : ui :主窗口* ui; QTcpServer *tserver; QTcpSocket *tsocket; private slots : voidlistenstartslot (; //开始侦听插槽void newConnectSlot (); //接收新连接的void receiveTcpSlot (); //槽函数是用于处理接收到的数据的void sendTcpSlot (; //TCP发送时隙(发送按钮触发) void tcpDisconnect ); //tcp连接中断//线程实验void closeThreadSlot (; (; #endif//mainwindow_h(2).mainwindow.cpp

# include ' main window.h ' # include ' ui _ main window.h ' main window 33603360 main window (q widget * parent ) 3360qmaindow //新的TCP服务器q object :3360连接(ui-listen button,signal ) clicked ) bool )、this、 slot ) listenstartslot ) ) )。//q object :3360 connect (this-t server,signal )、newconnection )、this、this //新连接的q object :3360 connect (ui-send button,signal ) clicked (bool )、this、 slot ) ) sendtcpslot ) ) ) ) ) ) 652 //发送数据//线程实验q object :3360 connect (ui-closethreadbuton,sclosethreadbuttton,s ) //线程实验pb=0; thread=newmythread(Pb; 趋势开始(; } main window :3360至main window () { tserver-close ); tserver-deleteLater (; 删除标题; //线程实验删除用户界面; ) void main window :3360 listenstartslot (/监听开始时隙(if(UI-listenbutton-text )='监听') quint16port=quint16 //if (! tserv

er->listen(QHostAddress::Any,port)) { QMessageBox::information(this,"提示","侦听设置出错"); return; } else { QMessageBox::information(this,"提示","开始侦听"); ui->listenButton->setText("取消侦听"); } } else { if(tsocket->state()==QAbstractSocket::ConnectedState) { tsocket->disconnectFromHost(); //关闭连接 } tserver->close(); //取消侦听 ui->listenButton->setText("侦听"); }}void MainWindow::newConnectSlot() //收到新连接{ tsocket=tserver->nextPendingConnection(); //server让自己的socket与client的socket相连 QObject::connect(this->tsocket,SIGNAL(disconnected()),this,SLOT(tcpDisconnect())); //套接字断开连接 QObject::connect(this->tsocket,SIGNAL(readyRead()),this,SLOT(receiveTcpSlot())); //收到数据 QMessageBox::information(this,"提示","侦听到新连接");}void MainWindow::receiveTcpSlot() //槽函数用于对接受的数据进行处理{ QByteArray receiveData; //因为传来的数据类型是未知的,用bytearray类型 receiveData=tsocket->readAll(); ui->receiveContextTextEdit->append(QString::fromUtf8(receiveData)); //}void MainWindow::sendTcpSlot() //发送tcp信号槽(发送按钮触发){ //发送图片 // qDebug()<<"sendPicture clicked"<<endl; // QPixmap pixmap(tr("th.jpg")); // QBuffer buffer; // buffer.open(QIODevice::ReadWrite); // pixmap.save(&buffer,"jpg"); // quint32 pixmap_len = (quint32)buffer.data().size(); // qDebug("image size:%d",pixmap_len); // QByteArray dataArray; // dataArray.append(buffer.data()); // quint32 write_len = tsocket->write(dataArray); // qDebug("write len:%d",write_len); //添加判断连接 QString sendContext=ui->sendContextTextEdit->document()->toPlainText();// tsocket->write(sendContext.toUtf8()); //以Utf8形式的bytearray发送 tsocket->flush();}void MainWindow::tcpDisconnect() //tcp连接中断{ ui->listenButton->setText("侦听"); QMessageBox::information(this,"提示","TCP连接中断");}void MainWindow::closeThreadSlot(){ delete thread;}

二、client端

(1).mainwindow.h

#ifndef MAINWINDOW_H#define MAINWINDOW_H#include <QMainWindow>#include <QTextCodec>//保证正常显示中文#include <QTcpSocket>#include <QDebug>#include <QMessageBox>#include <QByteArray>#include <QIODevice>#include <QBuffer>#include <QImageReader>#include <QDataStream> //数据流namespace Ui {class MainWindow;}class MainWindow : public QMainWindow{ Q_OBJECTpublic: explicit MainWindow(QWidget *parent = 0); ~MainWindow();private: Ui::MainWindow *ui; QTcpSocket *tsocket;private slots: void connectHostSlot(); //请求建立连接 void receiveTcpSlot(); //槽函数用于对接受的数据进行处理 void sendTcpSlot(); //发送tcp信号槽(发送按钮触发) void tcpDisconnect(); //tcp连接中断};#endif // MAINWINDOW_H

(2)mainwindow.cpp

#include "mainwindow.h"#include "ui_mainwindow.h"MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow){ ui->setupUi(this); tsocket =new QTcpSocket; //新建一个TCP套接字 QObject::connect(ui->connectButton,SIGNAL(clicked(bool)),this,SLOT(connectHostSlot())); //连接主机 QObject::connect(ui->sendButton,SIGNAL(clicked(bool)),this,SLOT(sendTcpSlot())); //发送数据 QObject::connect(tsocket,SIGNAL(readyRead()),this,SLOT(receiveTcpSlot())); //接收数据 QObject::connect(tsocket,SIGNAL(disconnected()),this,SLOT(tcpDisconnect())); //tcp连接中断}MainWindow::~MainWindow(){ delete ui; delete this->tsocket; //清理内存}void MainWindow::connectHostSlot() //请求建立连接{ if(ui->connectButton->text()=="连接") { QString hostip=ui->hostIpLineEdit->text(); //获取主机ip quint16 hostport=quint16(ui->hostPortLineEdit->text().toUInt()); //获取主机端口 tsocket->abort(); //取消已有连接 tsocket->connectToHost(hostip,hostport); //请求与服务器建立连接 if(!tsocket->waitForConnected(30000)) //等待30s { QMessageBox::information(this,"提示","连接失败"); return; } else { QMessageBox::information(this,"提示","连接成功"); ui->connectButton->setText("断开连接"); } } else { tsocket->disconnectFromHost(); //断开连接 ui->connectButton->setText("连接"); }}void MainWindow::receiveTcpSlot() //槽函数用于对接受的数据进行处理{// QByteArray array;// while(tsocket->waitForReadyRead(1)){ //连续接收 ,知道接收完毕// qDebug()<<"bytesAvailable"<<endl;// array.append((QByteArray)tsocket->readAll());// }//// QBuffer buffer(&array);// buffer.open(QIODevice::ReadOnly);//// QImageReader reader(&buffer,"JPG");// QImage img = reader.read();//// if(!img.isNull()){// qDebug()<<"right"<<endl;// ui->imageLabel->setPixmap(QPixmap::fromImage(img).scaled(ui->imageLabel->size()));//按比例缩放// } else {// qDebug()<<"error"<<endl;// } QByteArray receiveData; //因为传来的数据类型是未知的,用bytearray类型 receiveData=tsocket->readAll(); ui->receiveContextTextEdit->append(QString::fromUtf8(receiveData)); //转换成char *}void MainWindow::sendTcpSlot() //发送tcp信号槽(发送按钮触发){ //添加判断连接 QString sendContext=ui->sendContextTextEdit->document()->toPlainText();//// tsocket->write(sendContext.toLatin1()); tsocket->write(sendContext.toUtf8()); //将QString转换成QByteArray类型发送 tsocket->flush();}void MainWindow::tcpDisconnect() //tcp连接中断{ ui->connectButton->setText("连接"); QMessageBox::information(this,"提示","TCP连接中断");}

 

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。