QT Socket编程--TCP Server

来源:互联网 发布:马哥linux视频教程 编辑:程序博客网 时间:2024/05/22 06:14
1、在*.pro文件中添加:
QT += network

2、在代码中添加:

    QTcpServer *m_pTcpServer;   //server tcp socket    QTcpSocket *m_pConnectSocket;      //client connect socket        //初始化Socket    m_pTcpServer = new QTcpServer(this);    if (!m_pTcpServer->listen(QHostAddress::Any, port))    {//listen failqDebug()<<m_pTcpServer->errorString();QMessageBox::information(this, tr("Listen Fail"), m_pTcpServer->errorString());    }    connect(m_pTcpServer, SIGNAL(newConnection()), this, SLOT(slotConnectClient()));
//收到客户端连接void FormSocketSrv::slotConnectClient(){    m_pConnectSocket = m_pTcpServer->nextPendingConnection();    connect(m_pConnectSocket, SIGNAL(readyRead()), this, SLOT(slotReadTcpData()));    connect(m_pConnectSocket, SIGNAL(disconnected()),            m_pConnectSocket, SLOT(deleteLater()));    connect(m_pConnectSocket, SIGNAL(disconnected()),            this, SLOT(slotDisconnected()));}//接收数据void FormSocketSrv::slotReadTcpData(){    QByteArray byteArray;    byteArray = m_pConnectSocket->readAll();    //处理数据    processPakcet(byteArray);}//断开连接void FormSocketSrv::slotDisconnected(){}


原创粉丝点击