QT创建QTcpServer服务器

在MainWindow类中声明

QTcpSocket* m_ClientConnection;//服务器连接的客户端

QTcpServer *m_pTcpServer;

void MainWindow::OepnServer()
{
    m_ClientConnection = nullptr;
    //1. 创建TCP对象
    m_pTcpServer = new QTcpServer(this);
    //2. 新连接
    connect(m_pTcpServer, &QTcpServer::newConnection, this, &MainWindow::AppendClient);
    //3. 启动服务端
    QHostAddress *IP = new QHostAddress();
    IP->setScopeId("127.0.0.1");
    if (!m_pTcpServer->listen(*IP,4001))
    {
        qDebug() << "m_pTcpServer->listen() error";
    }
}

void  MainWindow::AppendClient()
{
    if(m_ClientConnection != nullptr)
    {
        m_ClientConnection->close();    
    }
    m_ClientConnection = m_pTcpServer->nextPendingConnection();
    connect(m_ClientConnection, &QIODevice::readyRead, this,&MainWindow::readyServer);
    connect(m_ClientConnection, &QTcpSocket::disconnected, this, &MainWindow::discountServer);
    qDebug() << "Append";
}


void  MainWindow:: discountServer()
{
    QTcpSocket* pQTcpSocket = static_cast(sender());
    qDebug()<<"receive disconnect!"<deleteLater();
    disconnect(pQTcpSocket, &QIODevice::readyRead, this,&MainWindow::readyServer);
    disconnect(pQTcpSocket, &QTcpSocket::disconnected, this, &MainWindow::discountServer);

    m_ClientConnection = nullptr;

}

void  MainWindow:: readyServer()
{
    QByteArray data = m_ClientConnection->readAll();
    
}

csdn文章推荐受影响解决办法10个字10行

csdn文章推荐受影响解决办法10个字10行

csdn文章推荐受影响解决办法10个字10行

csdn文章推荐受影响解决办法10个字10行

csdn文章推荐受影响解决办法10个字10行

csdn文章推荐受影响解决办法10个字10行

csdn文章推荐受影响解决办法10个字10行
 
 

你可能感兴趣的:(qt,qt,开发语言,c++,c语言)