QT关于网络TCP通讯的记录

来源:互联网 发布:阿里云新注册 编辑:程序博客网 时间:2024/05/16 08:19

  QT关于客户端和服务器端通过TCP连接通讯。直接上代码:

QTcpServer *m_pTCPSrv;//构建TCP服务器m_pTCPSrv = new QTcpServer(this);//关联成功接收连接的信号,当有新的连接的时候,调用槽函数onNewConnection()connect(m_pTCPSrv, SIGNAL(newConnection()), this,SLOT(onNewConnection()));void SvrListener::onNewConnection(){    //接收新连接    QTcpSocket *sockclient = m_pTCPSrv->nextPendingConnection();    //获取远端IP和端口    QString strIPAndPort = sockclient->peerAddress().toString() + tr(" : %1").arg(sockclient->peerPort());    //添加到列表    ui->listWidget->addItem(strIPAndPort);    //构建客户端对象    ClientJobs *pClientJob = new ClientJobs(this, sockclient, strIPAndPort);    //IP-port列表    m_listIPAndPorts.append(strIPAndPort);    //客户端列表    m_listClients.append(pClientJob);    connect(pClientJob, SIGNAL(CallMainWindowDeleteClient(QString)), this, SLOT(DeleteOneClient(QString)));    connect(pClientJob->m_pClientSock, SIGNAL(readyRead()),this,SLOT(readMessage())); //有可读的信息,触发读函数槽}

接收数据:

void SvrListener::readMessage() //读取信息{    QByteArray qba = m_listClients[m_nIndex] -> m_pClientSock -> readAll();    qDebug()<<qba;    QString ss=QVariant(qba).toString();    ui->textEditSvrMsg->setText(ss);}