Socke基类:
包括Socket的初始化,主要是windows上,在android上就不需要了
如果平台为windows,则需要初始化
- 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;
-
- #include<WinSock2.h>
- #pragmacomment(lib,"WS2_32.lib")
- #defineHSocketSOCKET
-
- #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
(编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|