what is the best way to make a network app? multi-thread...heart-beating...
-
Hi,
as I said before you don't necessarily need a Thread for this work; Do you need to receive data from server or request data to the server?
- Receive Data (f.i. using a UDP socket)
void ServerConnection::initSocket() { udpSocket = new QUdpSocket(this); udpSocket->bind(QHostAddress::LocalHost, 7755); connect(udpSocket, SIGNAL(readyRead()), this, SLOT(readPendingDatagrams())); } void ServerConnection::readPendingDatagrams() { while (udpSocket->hasPendingDatagrams()) { QByteArray datagram; datagram.resize(udpSocket->pendingDatagramSize()); QHostAddress sender; quint16 senderPort; udpSocket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort); processTheDatagram(datagram); } }
- Request Data
myTimer = new QTimer(this); connect(myTimer, &QTimer::timeout, this, &MyClass::requestData); void MyClass::requestData() { // Request data to the server }
-
thank you very much.
i dont use QUdpSocket..i use my own network classes.
right now i Tick the network io in the new thread. that's why i want to readData in msg loop, or heart-beating...maybe Tick the network io in the new thread, and use a timer as heart-beating in the main thread to readData() is a good method?
-
Hi,
if you don't need to use high-speed communication or a lot of data you can do the whole processing (tick and readData) without threads
-
u mean i can put all this in the Times' slot()?
-
and if i want high-speed communication or a lot of data, what should i do ?
it seems that u prefer not to create a new thread...why ? what is the disadvantage? -
Hi,
I think you should use something only if you really need it.
Qt is designed to work in asynchronous mode so you can handle multiple source of data in a single-thread application.You should move to multi-threading when you need the handle long time processing or when you need to non block who's sending you data.
-
thank you
i need the network io always Tick().
and i also need readData from the server all the time...eg. in a msg loop in windows..
but there seems no msg loop in Qt, so i wanted to use a timer as heart-beat to put readData in it. -
Hi,
do you need to read data only at tick?? In that case use the timeout signal to read data
connect (timer, &QTimer::timeout, this, &MyClass::readData); void MyClass::readData() { // Read from server }
-
yes,
in addition, i want to put the network io Tick into a new thread.
the readData() in the timeout slot. -
and what is the normal way to create a new thread? (i want sth like ::CreateThread in window)