您的位置:首页 > 理论基础 > 计算机网络

QT关于网络TCP通讯的记录

2017-06-12 23:23 375 查看
  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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: