zoukankan      html  css  js  c++  java
  • 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原创

  • 相关阅读:
    MyBatis Generator自动生成MyBatis的映射代码
    ajax 文件上传,ajax
    【学生必备求职指南】好简历是怎样炼成的?毕业生简历实例点评版 转载
    FC8下备份linux系统
    Fedora 18 安装前指南
    Fedora 18安装Google输入法和云拼音
    mfc radio group 设置
    MySQL Server 安装
    【转载】COM组件设计与应用(四)——简单调用组件
    【转载】COM组件设计与应用(三)——数据类型
  • 原文地址:https://www.cnblogs.com/kenter/p/1785066.html
Copyright © 2011-2022 走看看