#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_btn_connect_clicked()
{
quint16 port=ui->label_port->text().toUInt();
if(ser->listen(QHostAddress::Any,port))
{
QMessageBox::information(this,"服务器","连接成功");//有客户端连接会发来newconnection
connect(ser,&QTcpServer::newConnection,this,&Widget::slot_newconnection);
}
else
{
QMessageBox::information(this,"服务器","连接失败");
}
}
void Widget::slot_newconnection()
{
QTcpSocket *new_socket=ser->nextPendingConnection();
list_socket.push_back(new_socket);
connect(new_socket,&QTcpSocket::readyRead,this,&Widget::slot_readyread);
}
void Widget::slot_readyread()
{
for(int i=0;i<list_socket.count();i++)
{
if(list_socket.at(i)->state()==0)
{
list_socket.removeAt(i);
}
}
for(int j=0;j<list_socket.count();j++)
{
if(list_socket.at(j)->bytesAvailable()>0)
{
QByteArray msg=list_socket.at(j)->readAll();
ui->listWidget->addItem(QString::fromUtf8(msg));
for(int i=0;i<list_socket.count();i++)
{
list_socket.at(i)->write(msg);
}
}
}
}