代码:
#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()
{
quint16 port=ui->lineEdit->text().toUInt();
if(server->listen(QHostAddress::Any,port))
{
QMessageBox::information(this," ","服务器启动成功");
}
else
{
QMessageBox::information(this," ","服务器启动失败");
}
connect(server,&QTcpServer::newConnection,this,&Widget::newConnection_slot);
}
void Widget::newConnection_slot()
{
qDebug()<<"有新的饿了么订单,请及时处理";
//获取最新连接的客户端套接字
QTcpSocket* s= server->nextPendingConnection();
//将该套接字放到客户端容器中
sockerList.push_back(s);
connect(s,&QTcpSocket::readyRead,this,&Widget::readyread_slot);
}
void Widget::readyread_slot()
{
for(int i=0;i<sockerList.count();i++)
{
//sockerList.at(i)->state(); //任意一个客户端的状态
//返回值:套接字状态,是个枚举值,如果为0,表示无效链接
if(sockerList.at(i)->state()==0)
{
//移除该客户端 因为无效链接
sockerList.removeAt(i);
}
}
//遍历客户端套接字,寻找是哪个客户端有数据可读
for(int i=0;i<sockerList.count();i++)
{
if(sockerList.at(i)->bytesAvailable()!=0)
{
QByteArray msg=sockerList.at(i)->readAll();
//将数据展示到ui界面上
ui->msgWidget->addItem(QString::fromLocal8Bit(msg));
//将数据发送给所有客户端
for(int j=0;j<sockerList.count();j++)
{
sockerList.at(j)->write(msg);
}
}
}
}