qt学习|Qt TCP之Server/Client/Socket信号、槽等总结

mySocket类 自己封装的mySocket类,继承自QTcpSocket类。
常用的socket类的信号

  • disconnected() socket连接断开时触发
  • readyRead() 当有数据来到时触发该槽函数
常用的socket类的函数
  • connectToHost(serverIP,serverPort) 向服务器发起连接 指定IP和端口
Server类 自己封装的Server类,继承自QTcpServer类。生成实例化对象myTcpServer,然后对端口6666进行监听。如果在mainWindow中生成该实例化对象进行监听,总是监听不到端口,如果在main中生成实例话对象就可以,原因不清楚….监听:
Server myTcpServer; if(!myTcpServer.listen(QHostAddress::Any,port_ID))//port_ID 6666 { qDebug()<

在自己封装的Server类中去重写incomingConnection()函数,当监听到6666端口有新连接到来时,就会去执行incomingConnection()函数,就像keyPressEvent(QKeyEvent *eKey)函数一样,按下按键就自己去执行了。
void Server::incomingConnection(qintptr socketDescriptor) { qDebug()<<"new connection...."; mySocket*tempSocket = new mySocket; //将线程的父类设为连接的,防止内存泄露 QThread*tempThread = new QThread(tempSocket); if(!tempSocket->setSocketDescriptor(socketDescriptor)) { qDebug()<errorString(); return; } qDebug()<<"client IP is "<<(tempSocket->peerAddress().toString()); //客户端IP tempSocket->clientIP = tempSocket->peerAddress().toString(); getClientNum(tempSocket); connect(tempSocket,SIGNAL(disconnected()),tempThread,SLOT(quit())); //socket断开连接时,线程退出 connect(tempSocket,SIGNAL(disconnected()),tempSocket,SLOT(emitCrashSignal())); connect(tempSocket,SIGNAL(crashSocket(mySocket*)),this,SLOT(destorySocket(mySocket*))); connect(this,SIGNAL(newConnection()),tempSocket,SLOT(sendConnectSuccess())); //连接成功,告诉客户端tempSocket->moveToThread(tempThread); tempThread->start(); //开启线程 }

【qt学习|Qt TCP之Server/Client/Socket信号、槽等总结】其中的tempSocket->setSocketDescriptor(socketDescriptor)将socketDescriptor(该socket的描述符)从Server中传到new出来的tempsocket中。
qt学习|Qt TCP之Server/Client/Socket信号、槽等总结
文章图片

函数中有四个信号和槽的连接,其中属于QTcpServer类的信号是newConnection,当有客户端和服务器建立起新的连接时,触发该信号。槽函数是自己实现的,向客户端发送一条消息,告诉客户端已经建立连接。
另外,还将每个socket移入到一个新的线程中去,当连接断开时,线程自动退出,利用socket的disconnected信号和Qthread的quit槽函数实现。

    推荐阅读