1234567891011121314151617181920212223242526272829303132333435363738394041424344 |
- #include "mythread.h"
- MyThread::MyThread(QObject *parent): QThread(parent)
- {
- }
- void MyThread::MyThread::run()
- {
- //要处理的任务... 例如耗时3秒的操作
- // QThread::sleep(3);
- printf("this is MyThread");
- qDebug() << "this is MyThread begin:" << QThread::currentThreadId();
- //1.创建server对象
- QTcpServer* server=new QTcpServer(this);
- //2.设置服务器监听listen(ipAddr,port)
- bool res=server->listen(QHostAddress::Any,8018);//返回监听成功与否,可能存在端口占用情况
- qDebug() << "this is listen ret:" << res;
- //3.基于 QTcpServer::newConnection() 信号检测是否有新的客户端连接
- connect(server,&QTcpServer::newConnection,[=]()
- {
- QTcpSocket* tcpSocket=server->nextPendingConnection();//接收新的客户端连接,用于实际的收发处理
- qDebug() << "this is listen tcpSocket:" << tcpSocket;
- //4.收发处理,
- //4.1 当收到数据请求时,tcpSocket会发射readyread信号
- connect(tcpSocket,&QTcpSocket::readyRead,[=]()
- {
- //收到信息请求
- auto sMsg=tcpSocket->readAll();
- qDebug()<<"Datas from the remote client:"<<sMsg;
- });
- //4.2 写数据
- QByteArray sWriteMsg="Hello Client";
- tcpSocket->write(sWriteMsg);
- });
- qDebug() << "this is MyThread end:" << QThread::currentThreadId();
- //emit sign_stop(); //线程结束发送信号
- }
|