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

posted @ 2010-07-26 10:24  kenter  阅读(1556)  评论(0编辑  收藏  举报