class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
public slots:
void newConnect();
void readMessage(int i);
void onClick();
void displayError(QAbstractSocket::SocketError);
private:
Ui::Widget* ui;
QSignalMapper* mapper;
QTcpServer* tcpServer;
QTcpSocket* tcpSocket[8];
int socketID;
};
Widget::Widget(QWidget* parent):
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
tcpServer = new QTcpServer(this);
if(!tcpServer->listen(QHostAddress("10.2.100.63"),80))
{
QString error = tcpServer->errorString();
std::cout<<"error:"<<qPrintable(error)<<std::endl;
close();
}
socketID = -1;
mapper = new QSignalMapper(this);
connect(tcpServer,SIGNAL(newConnection()),this,SLOT(newConnect()));
connect(ui->ok,SIGNAL(clicked()),this,SLOT(onClick()));
connect(mapper,SIGNAL(mapped(int)),this,SLOT(readMessage(int)));
}
Widget::~Widget()
{
delete ui;
}
void Widget::readMessage(int i)
{
QString tag = tcpSocket[i]->readAll();
std::cout<<"result[0]:"<<tag.size()<<std::endl;
}
void Widget::displayError(QAbstractSocket::SocketError)
{
}
void Widget::newConnect()
{
socketID ++;
tcpSocket[socketID] = tcpServer->nextPendingConnection();
std::cout<<"connect:"<<tcpSocket[socketID]<<std::endl;
mapper->setMapping(tcpSocket[socketID],socketID);
connect(tcpSocket[socketID],SIGNAL(readyRead()),mapper,SLOT(map()));
}
void Widget::onClick()
{
if(socketID == -1)
return;
std::cout<<"send data:"<<std::endl;
QByteArray block;
for(int i=0;i<3000;i++)
{
block.append("123456");
}
for(int i=0;i<socketID;i++)
{
tcpSocket[i]->write(block.mid(i*block.size()/(i+2),block.size()/(i+2)));
}
ui->content->setPlainText(block.mid(block.size()*(socketID-1)/(2+socketID)));
}