Cpper
C/C++高级工程师 Android高级软件工程师 IT集成工程师 音频工程师 熟悉c,c++,java,c#,py,js,asp等多种语言 程序猿
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)));
}

posted on 2016-04-11 17:58 ccsdu2009 阅读(1402) 评论(0)  编辑 收藏 引用 所属分类: QT编程

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理