mythread.cpp 1.5 KB

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