QT服务器练习
#include "widget.h"
#include "ui_widget.h"Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget)
{ui->setupUi(this);//给服务器指针实例化空间server = new QTcpServer(this);
}Widget::~Widget()
{delete ui;
}//启动服务器按钮对应的槽函数
void Widget::on_startBtn_clicked()
{//获取ui界面上的端口号quint16 port = ui->portEdit->text().toUInt();//将服务器设置成监听状态if(server->listen(QHostAddress::Any, port)){QMessageBox::information(this,"","服务器启动成功");}else{QMessageBox::information(this,"","服务器启动失败");}//此时服务器已经进入监听状态connect(server,&QTcpServer::newConnection,this,&Widget::newConnection_slot);}
//处理newConnection信号的槽函数的实现
void Widget::newConnection_slot()
{qDebug()<<"新的客户端发来连接";//获取最新连接的客户端套接字QTcpSocket * s = server->nextPendingConnection();//将该套接字放入到客户端容器中socketList.push_back(s);connect(s,&QTcpSocket::readyRead,this,&Widget::readyRead_slot);
}
//关于readyRead信号对应的槽函数的实现
void Widget::readyRead_slot()
{//移除无效客户端for(int i = 0;i<socketList.count();i++){
// socketList.at(i)->state(); if(socketList.at(i)->state()==0){//移除该客户端socketList.removeAt(i);}}//遍历客户端套接字,寻找是哪个客户端有数据待读for(int i=0;i<socketList.count();i++){//判断当前套接字是否有数据待读if(socketList.at(i)->bytesAvailable() != 0){QByteArray msg = socketList.at(i)->readAll();//将该数据展示至UI界面上ui->msgWidget->addItem(QString::fromLocal8Bit(msg));//将数据发送给所有客户端for(int j = 0;j<socketList.count();j++){//将数据写入到所有客户端套接字中socketList.at(j)->write(msg);}}}
}
思维导图