首页 > 编程知识 正文

qt的tcp通信编程,qt socket编程实例

时间:2023-05-04 07:04:51 阅读:25526 作者:3367

英语注释都是从Qt助手那里抄来的,英语不好,不翻译。

启动程序时,必须先启动服务端,然后启动客户端才能连接。 如果在启动客户端后启动服务端,将无法连接。

我想在客户端建立一个死循环,一直检测连接是否成功,一直连接到连接为止,通过退出循环,即使先启动客户端也能连接。

客户端:

//构件. h # ifndef构件_ h # define构件_ h # includeqwidget # includeqhboxlayout # includeqvboxlayout # includeqpuput includeqbytearray # includeqstringclasswidget 3360 publicqwidget { q _ objectpublling } ~小部件(); void initUi (; //初始化接口void newTcpConnect (; //创建新的连接专用插槽3360语音发送消息; //发送消息的void receiveMessage (); //接收消息private: QTextEdit *myEdit,*yourEdit; QPushButton *sendButton,*closeButton; QHBoxLayout *hlayout; QVBoxLayout *vlayout,*alllayout; qtcpsocket*TCP插座; (; # endif//构件_ h//构件. CPP # include '构件. h '构件33603360构件(q构件* parent ) pareet 连接(close button,signal ) clicked(bool )、this,slot (close ) ) tcpSocket=new QTcpSocket; newTcpConnect (; //thissignalisemittedonceeverytimenewdataisavailableforreadingfromthedevice.connect (TCP套接字,信号) (readyread ) ) }语音构件:3360 init ui ((this-resize ) 500,500 ); 设置窗口标题(客户端); send button=newq push button (' send ',this ); close button=newq push button (' close ',this ); 我的编辑=newq textedit (this; YouRedit=newqtextedit(this; hlayout=new QHBoxLayout; hlayout-addstretch(6; h布局添加构件(关闭按钮; h布局添加构件(send button; vlayout=new QVBoxLayout; v layout-add构件(youredit,2 ); v layout-add构件(我的编辑,1 ); alllayout=new QVBoxLayout; alllayout-addlayout(vlayout; alllayout-addlayout(hlayout; 设置布局(al layout; } void构件:3360 newtcpconnect ()/abortsthecurrentconnectionandresetsthesocket.//unlikedisconnectfromhost ) ) ) thisfunctionimmediatelyclosesthesocket,discardinganypendingdatainthewritebuffer.TCP socket-abort; //attemptstomakeaconnectiontohostnameonthegive

n port. tcpSocket->connectToHost("127.0.0.1",9999);}void Widget::sendMessage(){ QString str = myEdit->toPlainText(); yourEdit->append(str); myEdit->clear(); QByteArray data = str.toUtf8(); tcpSocket->write(data);}void Widget::receiveMessage(){ //Reads all remaining data from the device, and returns it as a byte array. QByteArray data = tcpSocket->readAll(); QString str(data); yourEdit->append(str);}

Server:

//widget.h#ifndef WIDGET_H#define WIDGET_H#include <QWidget>#include <QHBoxLayout>#include <QVBoxLayout>#include <QPushButton>#include <QTextEdit>#include <QTcpSocket>#include <QTcpServer>#include <QAbstractSocket>#include <QByteArray>#include <QString>class Widget : public QWidget{ Q_OBJECTpublic: Widget(QWidget *parent = 0); ~Widget(); void initUi(); //初始化界面 void newListen(); //建立tcp监听事件private slots: void acceptConnect(); //接受客户端连接 void sendMessage(); //发送消息 void receiveMessage(); //接收消息private: QTextEdit *myEdit,*yourEdit; QPushButton *sendButton,*closeButton; QHBoxLayout *hlayout; QVBoxLayout *vlayout,*alllayout; QTcpServer *tcpServer; QTcpSocket *tcpSocket;};#endif // WIDGET_H//widget.cpp#include "widget.h"Widget::Widget(QWidget *parent) : QWidget(parent){ initUi(); tcpSocket = new QTcpSocket; tcpServer = new QTcpServer; newListen(); //This signal is emitted every time a new connection is available. connect(tcpServer,SIGNAL(newConnection()),SLOT(acceptConnect())); //This signal is emitted after an error occurred. //The socketError parameter describes the type of error that occurred. connect(tcpSocket,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(close()));}Widget::~Widget(){ delete tcpSocket; delete tcpServer;}void Widget::initUi(){ this->resize(500,500); this->setWindowTitle("Server"); sendButton = new QPushButton("send",this); closeButton = new QPushButton("close",this); myEdit = new QTextEdit(this); yourEdit = new QTextEdit(this); connect(sendButton,SIGNAL(clicked(bool)),this,SLOT(sendMessage())); connect(closeButton,SIGNAL(clicked(bool)),this,SLOT(close())); hlayout = new QHBoxLayout; hlayout->addStretch(6); hlayout->addWidget(closeButton); hlayout->addWidget(sendButton); vlayout = new QVBoxLayout; vlayout->addWidget(yourEdit,2); vlayout->addWidget(myEdit,1); alllayout = new QVBoxLayout; alllayout->addLayout(vlayout); alllayout->addLayout(hlayout); this->setLayout(alllayout);}void Widget::newListen(){ //Tells the server to listen for incoming connections on address address and port port. //If port is 0, a port is chosen automatically. If address is QHostAddress::Any, the server will listen on all network interfaces. if(!tcpServer->listen(QHostAddress::Any,9999)) { qDebug()<<tcpServer->errorString(); tcpServer->close(); }}void Widget::acceptConnect(){ //Returns the next pending connection as a connected QTcpSocket object. tcpSocket = tcpServer->nextPendingConnection(); connect(tcpSocket,SIGNAL(readyRead()),SLOT(receiveMessage()));}void Widget::sendMessage(){ QString str = myEdit->toPlainText(); yourEdit->append(str); myEdit->clear(); QByteArray data = str.toUtf8(); tcpSocket->write(data);}void Widget::receiveMessage(){ QByteArray data = tcpSocket->readAll(); QString str(data); yourEdit->append(str);}

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