Qt之QTcpServer/QTcpSocket簡單收發資訊(1)
阿新 • • 發佈:2019-01-09
用QT包裝好的東西做socket類東西,我只能說啥這麼簡單呢。
waitForConnected() 等待連結的建立
waitForReadyRead() 等待新資料的到來
waitForBytesWritten() 等待資料寫入socket
waitForDisconnected() 等待連結斷開
開始前在專案.pro裡面新增如下:
QT +=coreguinetwork
=========server==============
- #include "testnet.h"
- #include "ui_testnet.h"
- #include <QtGui>
- Testnet::Testnet(QWidget *parent) :
- QMainWindow(parent),
- ui(new Ui::Testnet)
- {
- ui->setupUi(this);
- this->connect(ui->pushButton_start,SIGNAL(clicked()),this,SLOT(startTcpserver()));
- this->connect(ui->pushButton_send,SIGNAL(clicked()),this,SLOT(sendMessage()));
- }
- Testnet::~Testnet()
- {
- delete
- }
- void Testnet::startTcpserver()
- {
- m_tcpServer = new QTcpServer(this);
- m_tcpServer->listen(QHostAddress::Any,19999); //監聽任何連上19999埠的ip
- connect(m_tcpServer,SIGNAL(newConnection()),this,SLOT(newConnect())); //新連線訊號觸發,呼叫newConnect()槽函式,這個跟訊號函式一樣,其實你可以隨便取。
- }
- void Testnet::newConnect()
- {
- m_tcpSocket = m_tcpServer->nextPendingConnection(); //得到每個連進來的socket
- connect(m_tcpSocket,SIGNAL(readyRead()),this,SLOT(readMessage())); //有可讀的資訊,觸發讀函式槽
- }
- void Testnet::readMessage() //讀取資訊
- {
- // ui->textEdit_rec->te
- QByteArray qba= m_tcpSocket->readAll(); //讀取
- qDebug()<<qba;
- QString ss=QVariant(qba).toString();
- ui->textEdit_rec->setText(ss);
- }
- void Testnet::sendMessage() //傳送資訊
- {
- QString strMesg= ui->lineEdit_sendmessage->text();
- qDebug()<<strMesg;
- m_tcpSocket->write(strMesg.toStdString().c_str(),strlen(strMesg.toStdString().c_str())); //傳送
- }
=======client========
- #include "testnet_c.h"
- #include "ui_testnet_c.h"
- testnet_c::testnet_c(QWidget *parent) :
- QMainWindow(parent),
- ui(new Ui::testnet_c)
- {
- ui->setupUi(this);
- this->connect(ui->pushButton_con,SIGNAL(clicked()),this,SLOT(connectServer()));
- this->connect(ui->pushButton_send,SIGNAL(clicked()),this,SLOT(sendMesg()));
- }
- testnet_c::~testnet_c()
- {
- delete ui;
- }
- void testnet_c::connectServer()
- {
- m_tcpSocket = new QTcpSocket(this);
- m_tcpSocket->abort();
- m_tcpSocket->connectToHost("192.168.1.178",19999);
- connect(m_tcpSocket,SIGNAL(readyRead()),this,SLOT(readMesg()));
- }
- void testnet_c::readMesg() //讀取資訊
- {
- QByteArray qba = m_tcpSocket->readAll();
- ui->textEdit_recmesg->clear();
- qDebug()<<qba;
- QString ss=QVariant(qba).toString();
- ui->textEdit_recmesg->setText(ss);
- }
- void testnet_c::sendMesg() //傳送資訊
- {
- QString ss= ui->lineEdit_sendmesg->text();
- m_tcpSocket->write(ss.toStdString().c_str(),strlen(ss.toStdString().c_str()));
- ui->lineEdit_sendmesg->clear();
- }