cocos2dx3.x利用sokcet创建客户端和服务端(一)

前端之家收集整理的这篇文章主要介绍了cocos2dx3.x利用sokcet创建客户端和服务端(一)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

Socke基类:

包括Socket的初始化,主要是windows上,在android上就不需要了

如果平台为windows,则需要初始化

  1. SocketBase::SocketBase()
  2. {
  3. _bInitSuccess=false;
  4. #if(CC_TARGET_PLATFORM==CC_PLATFORM_WIN32)
  5. WORDwVersionRequested;
  6. wVersionRequested=MAKEWORD(2,0);
  7. WSADATAwsaData;
  8. intnRet=WSAStartup(wVersionRequested,&wsaData);
  9. if(nRet!=0)
  10. fprintf(stderr,"InitilizeError!\n");
  11. return;
  12. }
  13. _bInitSuccess=true;
  14. #endif
  15. }


当然析构时也要释放资源

    SocketBase::~SocketBase()
  1. #if(CC_TARGET_PLATFORM==CC_PLATFORM_WIN32)
  2. if(_bInitSuccess)
  3. {
  4. WSACleanup();
  5. #endif
  6. 因为windows的socket()返回的socket句柄为SOCKET(UINT_PTR)

    与android的socket()返回的socket句柄int,类型不一样,所以都定义为HSocket

    对于服务端和客户端都有关闭连接,所以基类就实现共同的。

    voidSocketBase::closeConnect(HSocketsocket)
  1. #if(CC_TARGET_PLATFORM==CC_PLATFORM_ANDROID)
  2. close(socket);
  3. #elif(CC_TARGET_PLATFORM==CC_PLATFORM_WIN32)
  4. closesocket(socket);
  5. }

当执行socket()出错时,windows返回SOCKET_ERROR,android返回<0,

所以实现error()

    boolSocketBase::error(HSocketsocket)
  1. returnsocket==SOCKET_ERROR;
  2. #elif(CC_TARGET_PLATFORM==CC_PLATFORM_ANDROID)
  3. returnsocket<0;
  4. SocketBase.h

      #ifndef__SOCKET_BASE_H__
    1. #define__SOCKET_BASE_H__
    2. #include"cocos2d.h"
    3. #include<list>
    4. #include<thread>
    5. USING_NS_CC;
    6. //对于windows平台
    7. #include<WinSock2.h>
    8. #pragmacomment(lib,"WS2_32.lib")
    9. #defineHSocketSOCKET
    10. //对于android平台
    11. #include<arpa/inet.h>//forinet_**
    12. #include<netdb.h>//forgethost**
    13. #include<netinet/in.h>//forsockaddr_in
    14. #include<sys/types.h>//forsocket
    15. #include<sys/socket.h>//forsocket
    16. #include<unistd.h>
    17. #include<stdio.h>//forprintf
    18. #include<stdlib.h>//forexit
    19. #include<string.h>//forbzero
    20. #defineHSocketint
    21. classSocketBase:publicRef
    22. public:
    23. SocketBase();
    24. ~SocketBase();
    25. protected:
    26. voidcloseConnect(HSocketsocket);
    27. boolerror(HSocketsocket);
    28. std::mutex_mutex;
    29. private:
    30. bool_bInitSuccess;
    31. };
    32. #endif

    猜你在找的Cocos2d-x相关文章