QT模塊學習——TCP通訊(作業程序)
作業流程
對于通訊來說,通俗點講就是客戶端先去與服務器建立通訊,也就是發出請求,而在此時一直監聽著的服務器收到請求就是回應請求并同意連接,隨后發送,在發送成功后readyRead()便會對應做接受處理,

代碼
服務器
服務器需要兩個套接字,監聽套接字和通訊套接字
QTcpServer *tcpsever;
QTcpSocket *tcpsocket;
ui設計:
服務器:

#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
tcpsever=NULL;
tcpsocket=NULL;
setWindowTitle("埠號為8888的服務器");
tcpsever = new QTcpServer(this);
tcpsever->listen(QHostAddress::Any,8888);
connect(tcpsever,&QTcpServer::newConnection,
[=](){
tcpsocket = tcpsever->nextPendingConnection();
//獲得對方的IP和埠
QString ip = tcpsocket->peerAddress().toString();
qint16 port = tcpsocket->peerPort();
QString temp = QString("[%1:%2]:成功連接").arg(ip).arg(port);
ui->textEdit_2->setText(temp);
connect(tcpsocket, &QTcpSocket::readyRead,
[=](){
QByteArray array=tcpsocket->readAll();
ui->textEdit_2->append(array);
});
});
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_pushButton_send_clicked()
{
if(NULL==tcpsocket){
return;
}
//獲取編輯區內容
QString str = ui->textEdit->toPlainText();
tcpsocket->write(str.toUtf8().data());
}
void Widget::on_pushButton_2_clicked()
{
tcpsocket->disconnectFromHost();//
tcpsocket->close();
}
客戶端
僅僅需要一個通訊套接字
ui界面:

#include "client.h"
#include "ui_client.h"
#include <QHostAddress>
client::client(QWidget *parent) :
QWidget(parent),
ui(new Ui::client)
{
ui->setupUi(this);
tcpsocket = NULL;
tcpsocket = new QTcpSocket(this);
connect(tcpsocket, QTcpSocket::connected,
[=]()
{
ui->read->setText("成功與服務器建立連接");
}
);
connect(tcpsocket,&QTcpSocket::readyRead,
[=](){
QByteArray array = tcpsocket->readAll();
ui->read->setText(array);
});
}
client::~client()
{
delete ui;
}
void client::on_pushButton_3_clicked()
{
qint16 port = ui ->lineEdit->text().toInt();
QString ip = ui->lineEdit_2->text();
tcpsocket->connectToHost(QHostAddress(ip),port);//請求通訊
}
void client::on_pushButton_clicked()
{
QString str = ui->write->toPlainText();
tcpsocket->write(str.toUtf8().data());
ui->write->clear();
}
void client::on_pushButton_2_clicked()
{
tcpsocket->disconnectFromHost();
tcpsocket->close();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/57489.html
標籤:其他
下一篇:用C++實作多個資料冒泡排序
