pro添加
LIBS += -lws2_32
#ifndef WINSOCKET_H
#define WINSOCKET_H
#include <WinSock2.h>
#include <QThread>
class WinSocket : public QThread
{
Q_OBJECT
public:
explicit WinSocket();
~WinSocket();
void init(QString localIp,int localPort);
void sendData(char data[],int length,QString remoteIp,int remotePort);
private:
SOCKET msocket;
sockaddr_in localAddr;
sockaddr_in recvAddr;
sockaddr_in remoteAddr;
bool initSuccess;
char vrecvData[500];
char vsendData[500];
void run();
signals:
void sendRecvData(char *data,int length,QString recvIp);
public slots:
void dealRecvData(char *data,int length,QString recvIp);
};
#endif // WINSOCKET_H
#include "winsocket.h"
#include <QMessageBox>
#include <QDebug>
WinSocket::WinSocket()
{
initSuccess=false;
}
WinSocket::~WinSocket()
{
if(initSuccess)
{
::closesocket(msocket);
::WSACleanup();
requestInterruption();//要求中断
wait();//等待线程释放
}
}
void WinSocket::init(QString localIp,int localPort)
{
int retValue;
//初始化网络环境
WSADATA wsaData;
WORD sockVersion = MAKEWORD(2, 2);
retValue=::WSAStartup(sockVersion, &wsaData);
if(retValue!=0)
{
QMessageBox::information(NULL,"错误提示","Socket环境初始化失败");
return;
}
//创建socket
msocket = ::socket(AF_INET, SOCK_DGRAM, 0);
if (msocket == INVALID_SOCKET)
{
QMessageBox::information(NULL,"错误提示","创建socket出错");
::WSACleanup();
return;
}
localAddr.sin_family = AF_INET;
localAddr.sin_addr.s_addr = inet_addr(localIp.toLatin1());
localAddr.sin_port = ::htons(localPort);
//绑定函数
retValue= ::bind(msocket, (struct sockaddr*)&localAddr, sizeof(sockaddr_in));
if(retValue==-1)
{
QMessageBox::information(NULL,"错误提示","绑定IP和端口出错");
::closesocket(msocket);
::WSACleanup();
return;
}
//信号槽连接函数
connect(this,SIGNAL(sendRecvData(char *,int,QString)),this,SLOT(dealRecvData(char *,int,QString)));
//设置阻塞函数
int imode =0;
ioctlsocket(msocket,FIONBIO,(u_long FAR*)&imode);
if(retValue==SOCKET_ERROR)
{
QMessageBox::information(NULL,"错误提示","阻塞函数设置失败");
::closesocket(msocket);
::WSACleanup();
return;
}
//线程调用
start();
initSuccess=true;
}
void WinSocket::run()
{
int length=0;
int sockAddrSize=sizeof(sockaddr_in);
while(false==this->isInterruptionRequested())
{
memset(vrecvData,0,500);
length=0;
length=::recvfrom(msocket, (char*)vrecvData,sizeof(vrecvData), 0, (struct sockaddr*)&recvAddr, &sockAddrSize);
if(length!=-1)
{
memcpy(vsendData,vrecvData,length);
emit sendRecvData(vsendData,length,::inet_ntoa(recvAddr.sin_addr));
}
}
}
void WinSocket::dealRecvData(char data[],int length,QString recvIp)
{
qDebug()<<data<<" "<<length<<" "<<recvIp;
}
void WinSocket::sendData(char data[],int length,QString remoteIp,int remotePort)
{
if(initSuccess){
remoteAddr.sin_family = AF_INET;
remoteAddr.sin_addr.s_addr = ::inet_addr(remoteIp.toLatin1());
remoteAddr.sin_port = ::htons(remotePort);
::sendto(msocket, data,length,0, (sockaddr*)&remoteAddr,sizeof(sockaddr_in));
}
}
QT 调用windows socket
最新推荐文章于 2024-07-25 11:32:40 发布