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原创

  • 相关阅读:
    Java 装饰者模式
    struts2注解的作用
    XML DOM 笔记
    XMLHttpRequest的用法
    Eclipse中实现JS代码提示功能
    .after()和.before()的关系
    xml的的特殊字符转义&
    html和xml的区别
    dom4j的解析实例
    tld自定义标签系列--使用body-content的作用--比较有用
  • 原文地址:https://www.cnblogs.com/kenter/p/1785066.html
Copyright © 2011-2022 走看看