qt & QtUdpSocket

本文介绍如何通过使用QUdpSocket监控机器在线状态,利用多播socket自动发现IP地址,并详细阐述了如何将自定义结构体转换为字节数组进行数据传输,同时强调了在操作数据队列时使用互斥锁的重要性。此外,还提到了使用信号与槽机制进行事件响应。
摘要由CSDN通过智能技术生成

Today’s basic job is to watch over a machine and doing basic communication.

  1. How to watch over if the machine is online?
    Basic Idea: Because we are transferring Datagrams, so use QSocket.hasPendingDataGrams(). However the socket states changes very quickly, so use a for-loop to ‘wait’ until a datagram is received and if so, return true.

  2. How to auto-find the IP? Use multicast socket, then record the ip addr when recvdatagram() is called.

My_socket->bind(QHostAddress::AnyIPv4, m_LimitMPort,
                           QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint)
                           // return true if succesful
My_socket-> joinMulticastGroup(QHostAddress("224.224.224.224"))
  1. How to transfer my own defined structure?
    Cause I have defined a structure for data, I need to cast it to char* as this is qt pre-written function in writedatagram method call.
    Solution: use memcpy to copy my data into a char*, such as
int size = sizeof(My_struct1) + sizeof(My_struct2);
char* buffer[size] = 0;
memcpy(buffer, &transfer1, sizeof(My_struct1));
memcpy(buffer + sizeof(transfer1), &transfer2, sizeof(My_struct2));

Remember always do the pointer bias.
This also works when I have to parse a received bytes Array to my own defined struct.

*recorded_ = *((My_struct *)(m_BytesArray))
 // Firstly I cast the pointer type then I give the value to recorded, or the value get wasted.
  1. Always use mutex when operating on the data queue or vector,
  2. connect(socket, SIGNAL, Qobject, SLOT) means socket would operate SLOT when a SIGNAL is emitted and caught. It’s like abstract version of click the button and perform an action. (OnButtonClicked())
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值