?QT實(shí)現(xiàn)tcpf服務(wù)器代碼:(源文件)
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
//給服務(wù)器指針實(shí)例化空間
server = new QTcpServer(this);
}
Widget::~Widget()
{
delete ui;
}
//啟動(dòng)服務(wù)器按鈕對(duì)應(yīng)的槽函數(shù)
void Widget::on_startBtn_clicked()
{
//獲取ui界面上的端口
quint16 port = ui->portEdit->text().toInt();
//將服務(wù)器設(shè)置成監(jiān)聽(tīng)狀態(tài)
if(server->listen(QHostAddress::Any,port))
{
QMessageBox::information(this,"","服務(wù)器啟動(dòng)成功");
}
else
{
QMessageBox::information(this,"","服務(wù)器啟動(dòng)失敗");
}
//此時(shí)服務(wù)器已經(jīng)進(jìn)入監(jiān)聽(tīng)狀態(tài),如果有客戶端發(fā)來(lái)連接請(qǐng)求,那么該服務(wù)器就會(huì)自動(dòng)發(fā)射一個(gè)newConnection信號(hào)
//我們可以將該信號(hào)連接到自定義的槽函數(shù)中處理新連接的套接字
connect(server,&QTcpServer::newConnection,this,&Widget::newConnection_slot);
}
void Widget::newConnection_slot()
{
qDebug()<<"有新客戶連接";
//獲取最新連接的客戶端套接字
QTcpSocket *s=server->nextPendingConnection();
//將該套接字放入到客戶端容器中
socketlist.push_back(s);
//此時(shí),客戶端與服務(wù)器已經(jīng)建立起來(lái)連接
//如果有客戶端向服務(wù)器發(fā)來(lái)數(shù)據(jù),那么該客戶端會(huì)自動(dòng)發(fā)射一個(gè)readyRead信號(hào)
//我們可以在該信號(hào)對(duì)應(yīng)的槽函數(shù)中,讀取客戶端中的數(shù)據(jù)
connect(s,&QTcpSocket::readyRead,this,&Widget::readyRead_slot);
}
void Widget::readyRead_slot()
{
//移除無(wú)效客戶端
for(int i=0;i<socketlist.count();i++)
{
if(socketlist.at(i)->state()==0)
{
socketlist.removeAt(i);
}
}
//遍歷客戶端套接字,尋找是哪個(gè)客戶端有數(shù)據(jù)待讀
for(int i=0;i<socketlist.count();i++)
{
//判斷當(dāng)前套接字是否有數(shù)據(jù)待讀
if(socketlist.at(i)->bytesAvailable()!=0)
{
//讀取套接字中的所有數(shù)據(jù)
QByteArray msg = socketlist.at(i)->readAll();
//將數(shù)據(jù)展示到ui界面
ui->listWidget->addItem(QString::fromLocal8Bit(msg));
//將數(shù)據(jù)發(fā)送給所有客戶端
for(int j=0;j<socketlist.count();j++)
{
//將數(shù)據(jù)寫(xiě)入到所有客戶端套接字中
socketlist.at(j)->write(msg);
}
}
}
}
頭文件:
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QTcpServer>
#include <QTcpSocket>
#include <QMessageBox>
#include <QDebug>
#include <QList>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
private slots:
void on_startBtn_clicked();
void newConnection_slot();
void readyRead_slot();
private:
Ui::Widget *ui;
QTcpServer *server;
QList<QTcpSocket *> socketlist;
};
#endif // WIDGET_H
文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-615263.html
文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-615263.html
到了這里,關(guān)于QT--day4(定時(shí)器事件、鼠標(biāo)事件、鍵盤(pán)事件、繪制事件、實(shí)現(xiàn)畫(huà)板、QT實(shí)現(xiàn)TCP服務(wù)器)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!