qt学习|Qt TCP之Server/Client/Socket信号、槽等总结
mySocket类 自己封装的mySocket类,继承自QTcpSocket类。
常用的socket类的信号
- disconnected() socket连接断开时触发
- readyRead() 当有数据来到时触发该槽函数
- connectToHost(serverIP,serverPort) 向服务器发起连接 指定IP和端口
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信号、槽等总结](https://img.it610.com/image/info8/4a67c39bb4644f98a9a5a0f7e5ea4799.png)
文章图片
函数中有四个信号和槽的连接,其中属于QTcpServer类的信号是newConnection,当有客户端和服务器建立起新的连接时,触发该信号。槽函数是自己实现的,向客户端发送一条消息,告诉客户端已经建立连接。
另外,还将每个socket移入到一个新的线程中去,当连接断开时,线程自动退出,利用socket的disconnected信号和Qthread的quit槽函数实现。
推荐阅读
- CVE-2020-16898|CVE-2020-16898 TCP/IP远程代码执行漏洞
- PMSJ寻平面设计师之现代(Hyundai)
- 太平之莲
- 闲杂“细雨”
- 七年之痒之后
- 深入理解Go之generate
- 由浅入深理解AOP
- 期刊|期刊 | 国内核心期刊之(北大核心)
- 生活随笔|好天气下的意外之喜
- 感恩之旅第75天