1
0

UdpClientPage.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. #include "UdpClientPage.h"
  2. #include <QBoxLayout>
  3. #include "mainwindow.h"
  4. UdpClientPage::UdpClientPage(QWidget *parent) : QWidget(parent)
  5. {
  6. client = nullptr;
  7. initUI();
  8. initConnect();
  9. }
  10. UdpClientPage::~UdpClientPage()
  11. {
  12. stop();
  13. }
  14. void UdpClientPage::initUI()
  15. {
  16. QHBoxLayout* hbox = new QHBoxLayout;
  17. // host
  18. hbox->addWidget(new QLabel("host:"));
  19. hostEdt = new QLineEdit("127.0.0.1");
  20. hbox->addWidget(hostEdt);
  21. // port
  22. hbox->addWidget(new QLabel("port:"));
  23. portEdt = new QLineEdit("1234");
  24. hbox->addWidget(portEdt);
  25. // start
  26. startBtn = new QPushButton("start");
  27. hbox->addWidget(startBtn);
  28. // stop
  29. stopBtn = new QPushButton("stop");
  30. stopBtn->setEnabled(false);
  31. hbox->addWidget(stopBtn);
  32. setLayout(hbox);
  33. }
  34. void UdpClientPage::initConnect()
  35. {
  36. connect(startBtn, &QPushButton::clicked, [this]() {
  37. std::string host = hostEdt->text().toStdString();
  38. int port = portEdt->text().toInt();
  39. if (start(port, host.c_str())) {
  40. startBtn->setEnabled(false);
  41. stopBtn->setEnabled(true);
  42. g_mainwnd->appendMessage(QString::asprintf("UDP client sendto %s:%d ...", host.c_str(), port));
  43. } else {
  44. g_mainwnd->appendMessage(QString::asprintf("UDP client start failed!"));
  45. }
  46. });
  47. connect(stopBtn, &QPushButton::clicked, [this]() {
  48. stop();
  49. startBtn->setEnabled(true);
  50. stopBtn->setEnabled(false);
  51. g_mainwnd->appendMessage("UDP client stopped!");
  52. });
  53. }
  54. bool UdpClientPage::start(int port, const char* host)
  55. {
  56. client = new hv::UdpClient;
  57. int sockfd = client->createsocket(port, host);
  58. if (sockfd < 0) {
  59. return false;
  60. }
  61. client->onMessage = [](const hv::SocketChannelPtr& channel, hv::Buffer* buf) {
  62. g_mainwnd->postMessage(QString::asprintf("< %.*s", (int)buf->size(), (char*)buf->data()));
  63. };
  64. client->start();
  65. return true;
  66. }
  67. void UdpClientPage::stop()
  68. {
  69. SAFE_DELETE(client);
  70. }
  71. int UdpClientPage::send(const QString& msg)
  72. {
  73. if (client == nullptr) {
  74. g_mainwnd->postMessage("Please start first!");
  75. return -1;
  76. }
  77. return client->sendto(msg.toStdString());
  78. }