pro添加 LIBS += -lws2_32 #ifndef WINSOCKET_H #define WINSOCKET_H #include#include 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 #include 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()< 欢迎分享,转载请注明来源:内存溢出
QT 调用windows socket
赞
(0)
打赏
微信扫一扫
支付宝扫一扫
【狂神说Java】DoubleZookeeper初识
上一篇
2022-12-17
开发自己的SpringBoot Starter
下一篇
2022-12-17
评论列表(0条)