#include "server.h"Server::Server() : QObject(){ udpSock = new QUdpSocket(); connect(udpSock, SIGNAL(readyRead()), this, SLOT(readUDP())); timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(timeout())); stopSend = new QTimer(this); connect(stopSend, SIGNAL(timeout()), this, SLOT(stopSendMess())); stop = true;}Server :: ~Server(){ udpSock->close();}bool Server :: bind_port(quint16 port, quint16 _serverPort, QHostAddress _serverAddress){ if(udpSock->bind(port)) { serverPort = _serverPort; serverAddress = _serverAddress; emit message("Подключение выполнено"); udpsend = new UdpSend(serverAddress, serverPort);\ connect(udpsend, SIGNAL(finished()), udpsend, SLOT(deleteLater())); connect(this, SIGNAL(start(QUdpSocket*,bool*)), udpsend, SLOT(send(QUdpSocket*,bool*))); return true; } else emit message("Подключение не выполнено"); return false;}void Server::close_port(){ udpSock->close(); udpsend->quit(); emit message("Отключение выполнено");}void Server :: send_data_UDP(QString text){ QByteArray _message = text.toLocal8Bit(); QDataStream out(&_message, QIODevice::WriteOnly); out.setVersion(QDataStream :: Qt_4_8); udpSock->writeDatagram(_message, serverAddress, serverPort);}void Server :: readUDP(){ QByteArray receiveData; int nbytes = udpSock->pendingDatagramSize(); receiveData.resize(nbytes); udpSock->readDatagram (receiveData.data(), nbytes); emit append_message(receiveData); if(receiveData == "stop") stop = true; else if(stop) { stop = false; stopSend->start(1000); emit start(udpSock, &stop); }}void Server :: endless_send() //Через таймер работает хорошо, интерфейс не блокируется{ if(!stop) timer->start(1);}void Server :: timeout(){ timer->stop(); send_data_UDP("hello"); endless_send();}void Server :: stopSendMess(){ udpSock->close(); stop = true; stopSend->stop();}
#include "udpsend.h"UdpSend::UdpSend(QHostAddress _address, quint16 _port) : QThread(){ address = _address; port = _port; start(QThread :: LowestPriority);}void UdpSend :: run(){ exec();}void UdpSend :: send(QUdpSocket * udpSocket, bool * send){ QString text = "hello"; while(*send == false) { msleep(1); QByteArray _message = text.toLocal8Bit(); QDataStream out(&_message, QIODevice::WriteOnly); out.setVersion(QDataStream :: Qt_4_8); udpSocket->writeDatagram(_message, address, port); }}