• QT的网络TCP服务端端,支持多链路连接。


    定义

    #define TCPSOCKET_MAX 3 

     声明private变量

    QTcpServer *tcpServer;
    QList<QTcpSocket*> tcpSocketList; 

    声明public slots:

    public slots:
        void recv_slot();
        void connect_slot(); 

    //启动TCP服务
    void MainWindow::on_pushButton_3_clicked()
    {
        int tcpServerPort = ui->tcpServerPortText->text().toInt();
        //声明TCP服务
        this->tcpServer = new QTcpServer(this);
        //监听
        if(tcpServer->listen(QHostAddress::Any,tcpServerPort))
        {
            ui->pushButton_3->setEnabled(false);
            ui->pushButton_4->setEnabled(true);
        }
        //设置槽
        connect(tcpServer,SIGNAL(newConnection()),this,SLOT(connect_slot()));

    }

    //TCP服务连接事件
    void MainWindow::connect_slot()
    {

        if(tcpSocketList.count() <= TCPSOCKET_MAX)
        {
            QTcpSocket *tcpSocket = tcpServer -> nextPendingConnection();
            connect(tcpSocket,SIGNAL(readyRead()),this,SLOT(recv_slot()));
            tcpSocketList.append(tcpSocket);
        }

    }

    //TCP接收事件
    void MainWindow::recv_slot()
    {
        for(int i=0 ; i<tcpSocketList.count() ; i++)
        {
            QByteArray byte;
            QTcpSocket *tcpSocket=tcpSocketList.at(i);
            byte = tcpSocket -> readAll();
            QString result = printByteArr(byte);
            if(result.length()>0)
                addLog("tcp rev:" +tcpSocket->peerAddress().toString()+":"+ result);

            tcpSocket->write(strToQByteArray(result.mid(0,16)+ "17 01 03 14 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00"));
        }

    }

    //关闭TCP服务
    void MainWindow::on_pushButton_4_clicked()
    {
        tcpServer->close();
        ui->pushButton_3->setEnabled(true);
        ui->pushButton_4->setEnabled(false);

    转载请注明:kenter原创

  • 相关阅读:
    djano框架根据小牛深入研究
    python raise 是啥东西
    python调request报错
    python当前时间,时间偏移
    写好了,定时任务,怎么让定时任务,去在服务器上跑?
    python实现定时任务-目的解决自动化造数据
    django-celery
    Fruits【水果】
    The Extinction of Some Languages【一些语言的消失】
    Dawson City【道森市】
  • 原文地址:https://www.cnblogs.com/kenter/p/1785066.html
Copyright © 2020-2023  润新知