Today’s basic job is to watch over a machine and doing basic communication.
-
How to watch over if the machine is online?
Basic Idea: Because we are transferring Datagrams, so useQSocket.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. -
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"))
- 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.
- Always use mutex when operating on the data queue or vector,
- 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())