为创建一个线程,子类化QThread并且重写它的run()函数,例如:
mainwindow.h
=====================
定义线程类
class udp_thread;
定义线程指针
udp_thread * m_pudp_thread;
声明线程
class udp_thread:public QThread
{
public:
udp_thread(MainWindow *pWnd);
~udp_thread();
void run();
public:
MainWindow *pWnd;
};
mainwindow.cpp
=====================
创建线程
m_pudp_thread=new udp_thread(this);
在某个地方启动线程
设置它的优先级,当然也可以不带,使用默认的优先级m_pudp_thread->start(QThread::LowestPriority);
重新实现类中函数
void udp_thread::run()
{
int ret;
char buf[512]={" fine"};
int sockfd;
struct sockaddr_in serv_addr;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd == -1){
printf("socket error!");
return ;
}
bzero(&serv_addr, sizeof serv_addr);
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(UDP_PORT);
serv_addr.sin_addr.s_addr = INADDR_ANY;
while(1) {
sendto(sockfd, buf, strlen(buf), 0, (struct sockaddr *)&serv_addr, sizeof serv_addr); //接收数据
sleep(1);
}
close(sockfd);
}
udp_thread::udp_thread(MainWindow *pMainWnd)
{
pWnd=pMainWnd;
}
udp_thread::~udp_thread()
{
}
阅读(1185) | 评论(0) | 转发(0) |