• Qt Socket 通讯示例2


    服务端代码

    1. // MyTcpSocket.h
    2. #ifndef MYTCPSOCKET_H
    3. #define MYTCPSOCKET_H
    4. #include
    5. #include
    6. #pragma execution_character_set("utf-8")
    7. class MyTcpSocket : public QTcpSocket
    8. {
    9. Q_OBJECT
    10. public:
    11. MyTcpSocket(QObject *parent = 0);
    12. ~MyTcpSocket();
    13. void ServerWriteData();
    14. signals:
    15. void sigSocketRecvData(QString, int);
    16. void sigSocketDisconnect(int);
    17. public slots:
    18. void OnReadyReadSignal();
    19. void OnDisconnectedSignal();
    20. private:
    21. static int m_nIndex;
    22. };
    23. #endif // MYTCPSOCKET_H
    1. // MyTcpSocket.cpp
    2. #include "MyTcpSocket.h"
    3. int MyTcpSocket::m_nIndex = 0;
    4. MyTcpSocket::MyTcpSocket(QObject *parent):
    5. QTcpSocket(parent)
    6. {
    7. connect(this, SIGNAL(readyRead()), this, SLOT(OnReadyReadSignal())); //准备接收
    8. connect(this, SIGNAL(disconnected()), this, SLOT(OnDisconnectedSignal())); //断开连接信号
    9. }
    10. MyTcpSocket::~MyTcpSocket()
    11. {
    12. }
    13. void MyTcpSocket::ServerWriteData()
    14. {
    15. QString strMsg = QString("World ... %1").arg(m_nIndex++);
    16. //int nSendRet = write(strMsg.toUtf8().data());
    17. int nSendRet = write(strMsg.toLatin1(), strMsg.length());
    18. waitForBytesWritten();
    19. if (-1 == nSendRet)
    20. {
    21. qDebug() << "Failed to send data " << strMsg;
    22. }
    23. else
    24. {
    25. qDebug() << "Send data: " << strMsg << endl;
    26. return;
    27. }
    28. }
    29. void MyTcpSocket::OnReadyReadSignal()
    30. {
    31. qDebug() << "On singal ... readyRead";
    32. while(this->bytesAvailable() > 0) //检查字节数
    33. {
    34. char buf[1024] = { 0 };
    35. int length = bytesAvailable();
    36. this->read(buf, length); //读取接收
    37. QString message = QString(QLatin1String(buf));
    38. qDebug() << "socket recv: " << message;
    39. emit sigSocketRecvData(message, length); //发射信号
    40. ServerWriteData();
    41. }
    42. }
    43. void MyTcpSocket::OnDisconnectedSignal()
    44. {
    45. qDebug() << "On singal ... Disconnected!";
    46. emit sigSocketDisconnect(this->socketDescriptor());
    47. }
    1. // MyTcpServer.h
    2. #ifndef MYTCPSERVER_H
    3. #define MYTCPSERVER_H
    4. #include "MyTcpSocket.h"
    5. #include
    6. class MyTcpServer : public QTcpServer
    7. {
    8. Q_OBJECT
    9. public:
    10. explicit MyTcpServer(QObject *parent = 0);
    11. ~MyTcpServer();
    12. void MyTcpServerListen();
    13. protected:
    14. //void incomingConnection(int socketDescriptor);
    15. void incomingConnection(qintptr socketDescriptor);
    16. signals:
    17. void sigServerRecvData(QString, int);
    18. public slots:
    19. void OnSocketRecvDataSignal(QString,int);
    20. void OnSocketDisconnectSignal(int);
    21. private:
    22. QList tcpSocketList;
    23. //协议端口号
    24. int m_nPort;
    25. };
    26. #endif // MYTCPSERVER_H
    1. // MyTcpServer.cpp
    2. #include "MyTcpServer.h"
    3. #include
    4. MyTcpServer::MyTcpServer(QObject *parent) :
    5. QTcpServer(parent)
    6. {
    7. m_nPort = 8010;
    8. }
    9. MyTcpServer::~MyTcpServer()
    10. {
    11. for (int n = 0; n < tcpSocketList.size(); ++n)
    12. {
    13. MyTcpSocket *item = (MyTcpSocket *)tcpSocketList.at(n);
    14. if (NULL != item)
    15. {
    16. qDebug() << "MyTcpServer destruct ... " << n;
    17. delete item;
    18. item = NULL;
    19. }
    20. }
    21. }
    22. void MyTcpServer::MyTcpServerListen()
    23. {
    24. this->listen(QHostAddress::Any, m_nPort); //监听本机的 IP 地址和端口
    25. qDebug() << "Start listening port:" << m_nPort;
    26. waitForNewConnection(10000);
    27. }
    28. //void MyTcpServer::incomingConnection(int socketDescriptor)
    29. void MyTcpServer::incomingConnection(qintptr socketDescriptor)
    30. {
    31. qDebug()<< "new client connect ... ";
    32. MyTcpSocket *tcpSocket = new MyTcpSocket(this);
    33. QString ip = tcpSocket->peerAddress().toString();
    34. qint16 port = tcpSocket->peerPort();
    35. qDebug() << "IP: " << ip << " ... Port: " << (uint16_t)port << endl;
    36. connect(tcpSocket, SIGNAL(sigSocketRecvData(QString,int)), this, SLOT(OnSocketRecvDataSignal(QString,int)));
    37. connect(tcpSocket, SIGNAL(sigSocketDisconnect(int)), this, SLOT(OnSocketDisconnectSignal(int)));
    38. tcpSocket->setSocketDescriptor(socketDescriptor);
    39. tcpSocketList.append(tcpSocket); //在 list 末尾插入数据
    40. tcpSocket->waitForDisconnected(8000);
    41. }
    42. void MyTcpServer::OnSocketRecvDataSignal(QString message, int length)
    43. {
    44. qDebug() << "server recv ..." << message;
    45. //emit sigServerRecvData(message, length); //发射信号
    46. //for(int i = 0; i < tcpSocketList.count(); i++)
    47. //{
    48. // QTcpSocket *temp = tcpSocketList.at(i);
    49. // if(temp->write(message.toLatin1(), length) != length)
    50. // {
    51. // continue;
    52. // }
    53. //}
    54. }
    55. void MyTcpServer::OnSocketDisconnectSignal(int descriptor)
    56. {
    57. qDebug() << "server disconnect ..." ;
    58. for(int i = 0; i < tcpSocketList.count(); i++)
    59. {
    60. QTcpSocket *temp = tcpSocketList.at(i);
    61. if(temp->socketDescriptor() == descriptor)
    62. {
    63. tcpSocketList.removeAt(i);
    64. delete temp;
    65. temp = NULL;
    66. qDebug() << "temp destruct ..." << i;
    67. return;
    68. }
    69. }
    70. return;
    71. }
    1. #include
    2. #include "MyTcpServer.h"
    3. int main(int argc, char *argv[])
    4. {
    5. QCoreApplication a(argc, argv);
    6. //实例 tcpServer
    7. MyTcpServer *tcpServer = new MyTcpServer(nullptr);
    8. tcpServer->MyTcpServerListen();
    9. //std::this_thread::sleep_for(std::chrono::seconds(15));
    10. delete tcpServer;
    11. tcpServer = NULL;
    12. qDebug() << "server over ...";
    13. return a.exec();
    14. }

    客户端代码

    1. // MyTcpClient.h
    2. #pragma once
    3. #include
    4. #include
    5. #include
    6. #pragma execution_character_set("utf-8")
    7. class MyTcpClient : public QObject
    8. {
    9. Q_OBJECT
    10. public:
    11. MyTcpClient(QObject *parent);
    12. ~MyTcpClient();
    13. void MyTcpConnect();
    14. void MyTcpDisconnect();
    15. void MyWriteData();
    16. private slots:
    17. void OnDisconnectSignal();
    18. void OnReadyReadSignal();
    19. private:
    20. QTcpSocket *m_pTcpSocket;
    21. QString m_strIP;
    22. int m_nPort;
    23. int m_nIndex;
    24. };
    1. // MyTcpClient.cpp
    2. #include "MyTcpClient.h"
    3. MyTcpClient::MyTcpClient(QObject *parent)
    4. : QObject(parent)
    5. {
    6. m_strIP = "127.0.0.1";
    7. m_nPort = 8010;
    8. m_nIndex = 0;
    9. }
    10. MyTcpClient::~MyTcpClient()
    11. {
    12. if (NULL != m_pTcpSocket)
    13. {
    14. qDebug() << "MyTcpClient destruct";
    15. delete m_pTcpSocket;
    16. m_pTcpSocket = nullptr;
    17. }
    18. }
    19. void MyTcpClient::MyTcpConnect()
    20. {
    21. qDebug() << "client connect ... ";
    22. m_pTcpSocket = new QTcpSocket(this);
    23. //connect(m_pTcpSocket, SIGNAL(connected()), this, SLOT(tcpConnected()));
    24. connect(m_pTcpSocket, SIGNAL(readyRead()), this, SLOT(OnReadyReadSignal()));
    25. //connect(m_pTcpSocket, SIGNAL(disconnected()), this, SLOT(OnDisconnectSignal()));
    26. m_pTcpSocket->connectToHost(m_strIP, m_nPort);
    27. m_pTcpSocket->waitForConnected(30000);
    28. }
    29. void MyTcpClient::MyTcpDisconnect()
    30. {
    31. OnDisconnectSignal();
    32. }
    33. void MyTcpClient::MyWriteData()
    34. {
    35. QString strMsg = QString("Hello ... %1").arg(m_nIndex++);
    36. char bufferMsg[1024] = { 0 };
    37. strcpy_s(bufferMsg, strMsg.toStdString().c_str());
    38. int nSendRet = m_pTcpSocket->write(bufferMsg, strlen(bufferMsg));
    39. //int nSendRet = m_pTcpSocket->write(strMsg.toUtf8().data());
    40. m_pTcpSocket->waitForBytesWritten();
    41. if (-1 != nSendRet)
    42. {
    43. qDebug() << "Send data: " << strMsg;
    44. }
    45. else
    46. {
    47. qDebug() << "Failed to send data " << strMsg;
    48. }
    49. return;
    50. }
    51. void MyTcpClient::OnDisconnectSignal()
    52. {
    53. qDebug() << "client disconnect ... ";
    54. m_pTcpSocket->waitForDisconnected(1000);
    55. //主动和对方断开连接
    56. m_pTcpSocket->disconnectFromHost();
    57. m_pTcpSocket->close();//这里释放连接,前面connect的时候会建立连接
    58. }
    59. void MyTcpClient::OnReadyReadSignal()
    60. {
    61. while (m_pTcpSocket->bytesAvailable() > 0)
    62. {
    63. QByteArray datagram;
    64. datagram.resize(m_pTcpSocket->bytesAvailable());
    65. m_pTcpSocket->read(datagram.data(), datagram.length());
    66. //m_pTcpSocket->waitForReadyRead(1000);
    67. QString message = datagram.data();
    68. //listWidget->addItem(message);
    69. qDebug() << "Recv data: "<< message;
    70. }
    71. }
    1. // main.cpp
    2. #include
    3. #include "MyTcpClient.h"
    4. int main(int argc, char *argv[])
    5. {
    6. QCoreApplication a(argc, argv);
    7. MyTcpClient* client = new MyTcpClient(nullptr);
    8. client->MyTcpConnect();
    9. for (int n = 0; n < 3; n++)
    10. {
    11. client->MyWriteData();
    12. std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    13. }
    14. std::this_thread::sleep_for(std::chrono::seconds(1));
    15. client->MyTcpDisconnect();
    16. delete client;
    17. client = NULL;
    18. qDebug() << "client over ...";
    19. return a.exec();
    20. }

  • 相关阅读:
    每日一题(LeetCode)----数组--螺旋矩阵(一)
    vue2技能树(5)-条件渲染和列表渲染
    C语言入门(七)while和do-while循环
    全链路压测效能10倍提升的压测工具实践笔记
    是时候重视官网了,寄生平台的生意表达,就是在给平台打工
    LeetCode中等题之二叉树的层序遍历
    C-语言每日刷题
    大学生个人网页模板 简单网页制作作业成品 极简风格个人介绍HTML网页设计代码下载
    sqlmap用户手册(七)——爆破等
    Ubuntu20.04配置CUDA+CUDNN深度学习环境
  • 原文地址:https://blog.csdn.net/youqingyike/article/details/126787148