Socke基类:
包括Socket的初始化,主要是windows上,在androID上就不需要了
如果平台为windows,则需要初始化
[cpp] view plain copy SocketBase::SocketBase() { _bInitSuccess=false; #if(CC_TARGET_PLATFORM==CC_PLATFORM_WIN32) WORDwVersionRequested; wVersionRequested=MAKEWORD(2,0); WSADATAwsaData; intnRet=WSAStartup(wVersionRequested,&wsaData); if(nRet!=0) fprintf(stderr,"InitilizeError!\n"); return; } _bInitSuccess=true; #endif }
当然析构时也要释放资源
SocketBase::~SocketBase() #if(CC_TARGET_PLATFORM==CC_PLATFORM_WIN32) if(_bInitSuccess) { WSACleanup(); #endif 因为windows的socket()返回的socket句柄为SOCKET(UINT_PTR)
与androID的socket()返回的socket句柄int,类型不一样,所以都定义为HSocket
voIDSocketBase::closeConnect(HSocketsocket) #if(CC_TARGET_PLATFORM==CC_PLATFORM_ANDROID) close(socket); #elif(CC_TARGET_PLATFORM==CC_PLATFORM_WIN32) closesocket(socket); }
当执行socket()出错时,windows返回SOCKET_ERROR,androID返回<0,
所以实现error()
boolSocketBase::error(HSocketsocket) returnsocket==SOCKET_ERROR; #elif(CC_TARGET_PLATFORM==CC_PLATFORM_ANDROID) returnsocket<0; SocketBase.h
#ifndef__SOCKET_BASE_H__ #define__SOCKET_BASE_H__ #include"cocos2d.h" #include<List> #include<thread> USING_NS_CC; //对于windows平台 #include<WinSock2.h> #pragmacomment(lib,"WS2_32.lib") #defineHSocketSOCKET //对于androID平台 #include<arpa/inet.h>//forinet_** #include<netdb.h>//forgethost** #include<netinet/in.h>//forsockaddr_in #include<sys/types.h>//forsocket #include<sys/socket.h>//forsocket #include<unistd.h> #include<stdio.h>//forprintf #include<stdlib.h>//forexit #include<string.h>//forbzero #defineHSocketint classSocketBase:publicRef public: SocketBase(); ~SocketBase(); protected: voIDcloseConnect(HSocketsocket); boolerror(HSocketsocket); std::mutex_mutex; private: bool_bInitSuccess; }; #endif 总结
以上是内存溢出为你收集整理的cocos2dx3.x利用sokcet创建客户端和服务端(一)全部内容,希望文章能够帮你解决cocos2dx3.x利用sokcet创建客户端和服务端(一)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)