#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);
}
}
}
}
思维导图