#include "mythread.h"
#include "widget.h"
MyThread::MyThread(QObject *parent) :
m_Widget(static_cast<Widget*>(parent))
{
bool ok;
moveToThread(this);
localip = "192.168.41.1";
Sendip = "192.168.41.1";
port = 8888;
SendPort = 8000;
udpFlag = 0;
localip.toIPv4Address(&ok);
if(!ok)
{
qDebug()<<"本地ip设置有误";
return ;
}
}
MyThread::~MyThread()
{
if(udpSocket != nullptr)
{
udpSocket->abort();
delete udpSocket;
}
}
void MyThread::run()//线程处理函数
{
udpSocket = new QUdpSocket(this);
/* 绑定端口需要在socket的状态为UnconnectedState */
if (udpSocket->state() != QAbstractSocket::UnconnectedState)
udpSocket->close();
if (udpSocket->bind(localip,port)) {
qDebug()<<"已经成功绑定:"<<localip.toString()<<":"<< QString::number(port);
udpFlag = 1;
}
connect(this->m_Widget,&Widget::WriteMessage, this,&MyThread::sendMessages,Qt::BlockingQueuedConnection);
connect(udpSocket,SIGNAL(stateChanged(QAbstractSocket::SocketState)),this,SLOT(socketStateChange(QAbstractSocket::SocketState)));
connect(udpSocket, SIGNAL(readyRead()), this, SLOT(receiveMessages()));
// qDebug()<<"obj thread: "<<QThread::currentThreadId();
exec();
}
void MyThread::socketStateChange(QAbstractSocket::SocketState state)
{
switch (state) {
case QAbstractSocket::UnconnectedState:
qDebug()<<("scoket状态:UnconnectedState");
break;
case QAbstractSocket::ConnectedState:
qDebug()<<("scoket状态:ConnectedState");
break;
case QAbstractSocket::ConnectingState:
qDebug()<<("scoket状态:ConnectingState");
break;
case QAbstractSocket::HostLookupState:
qDebug()<<("scoket状态:HostLookupState");
break;
case QAbstractSocket::ClosingState:
qDebug()<<("scoket状态:ClosingState");
break;
case QAbstractSocket::ListeningState:
qDebug()<<("scoket状态:ListeningState");
break;
case QAbstractSocket::BoundState:
qDebug()<<("scoket状态:BoundState");
break;
default:
break;
}
}
void MyThread::sendMessages(QByteArray ba)
{
/* 广播地址,一般为255.255.255.255,
* 同一网段内监听目标端口的程序都会接收到消息 */
QHostAddress peerAddr = QHostAddress::Broadcast;
qDebug()<<ba.size()<<Sendip.toString();
qDebug()<<"write thread: "<<QThread::currentThreadId();
/* 发送消息 */
udpSocket->writeDatagram(ba, Sendip, SendPort);
}
/* 客户端接收消息 */
void MyThread::receiveMessages()
{
/* 局部变量,用于获取发送者的IP和端口 */
QHostAddress peerAddr;
quint16 peerPort;
qDebug()<<"read thread: "<<QThread::currentThreadId();
/* 如果有数据已经准备好 */
while (udpSocket->hasPendingDatagrams()) {
/* udpSocket发送的数据报是QByteArray类型的字节数组 */
QByteArray datagram;
/* 重新定义数组的大小 */
datagram.resize(udpSocket->pendingDatagramSize());
/* 读取数据,并获取发送方的IP地址和端口 */
udpSocket->readDatagram(datagram.data(),
datagram.size(),
&peerAddr,
&peerPort);
/* 转为字符串 */
QString str = datagram.data();
qDebug()<<"接收来自"<<peerAddr.toString()<<":"<<QString::number(peerPort)<<str;
qDebug()<<"read thread: "<<QThread::currentThreadId()<<datagram.size();
}
}