Qt实现简单的TCP协议(客户端的实现)

it2022-05-30  85

1、QT提供了QTcpSocket类,可以直接实例化一个客户端。需要在pro文件中添加   QT += network

2、连接服务端

connect(connectbutton,SIGNAL(clicked()),this,SLOT(on_connect_cliked()));

 

void MyDialog::on_connect_cliked(){ if(connectbutton->text()=="连接") { m_socket->connectToHost("192.168.0.103",8899,QTcpSocket::ReadWrite); if(!m_socket->waitForConnected()) { qDebug()<<"client connect error"; } else{ qDebug()<<"已连接上"; connectbutton->setText("断开"); } } else { m_socket->disconnectFromHost(); if(m_socket->state()==QAbstractSocket::UnconnectedState || m_socket->waitForDisconnected(1000)) { qDebug()<<"已断开"; connectbutton->setText("连接"); } } }3、接受服务端发来的数据 QTimer *timer = new QTimer; connect(timer,SIGNAL(timeout()),this,SLOT(receive_repeat())); timer->start(1); void MyDialog::readData(){ QByteArray buffer = m_socket->readAll(); if(!buffer.isEmpty()) { receivee.append(buffer); qDebug()<<"添加了数据"; } }4、给服务端发送数据 connect(sendbutton,SIGNAL(clicked()),this,SLOT(send_msg())); void MyDialog::send_msg(){ QString data = sendtext->toPlainText(); if(data != "") { // qDebug()<<"mydialog sendtext2"<<data; m_socket->write(data.toLatin1()); } }

转载于:https://www.cnblogs.com/LeorI/p/9970678.html

相关资源:Qt利用TCP实现客户端与服务器端的数据传输

最新回复(0)