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

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

客户端:

连接服务端

boolconnectServer(constchar*serverIP,unsignedshortport);

向服务端发送消息

voidsendMessage(char*data,255)">intcount);

接受服务端数据的回调函数

std::function<void(intcount)>onRecv;

断开连接的回调函数

void()>onDisconnect;

SocketClient.h

  1. #ifndef__SOCKET_CLIENT_H__
  2. #define__SOCKET_CLIENT_H__
  3. #include"SocketBase.h"
  4. classSocketClient:publicSocketBase
  5. {
  6. public:
  7. SocketClient(void);
  8. ~SocketClient(void);
  9. boolconnectServer(constchar*serverIP,unsignedshortport);
  10. voidsendMessage(char*data,intcount);
  11. std::function<void(intcount)>onRecv;
  12. std::function<void()>onDisconnect;
  13. private:
  14. boolinitClient();
  15. voidrecvMessage();
  16. HSocket_socketServer;
  17. HSocket_socektClient;
  18. };
  19. #endif

SocketClient.cpp

    #include"SocketClient.h"
  1. SocketClient::SocketClient(void):
  2. onRecv(nullptr),
  3. _socektClient(0)
  4. {
  5. }
  6. SocketClient::~SocketClient(void)
  7. if(_socektClient!=0)
  8. _mutex.lock();
  9. this->closeConnect(_socektClient);
  10. _mutex.unlock();
  11. }
  12. boolSocketClient::initClient()
  13. _socektClient=socket(AF_INET,SOCK_STREAM,0);
  14. if(error(_socketServer))
  15. log("initclienterror!");
  16. _socektClient=0;
  17. returnfalse;
  18. true;
  19. boolSocketClient::connectServer(shortport)
  20. if(!this->initClient())
  21. structsockaddr_inserverAddr;
  22. memset(&serverAddr,sizeof(structsockaddr_in));
  23. serverAddr.sin_family=AF_INET;
  24. serverAddr.sin_port=htons(port);
  25. serverAddr.sin_addr.s_addr=inet_addr(serverIP);
  26. intret=0;
  27. ret=connect(_socektClient,(structsockaddr*)&serverAddr,structsockaddr));
  28. if(ret<0)
  29. this->closeConnect(_socektClient);
  30. std::threadrecvThread(&SocketClient::recvMessage,153); font-weight:bold; background-color:inherit">this);
  31. recvThread.detach();
  32. voidSocketClient::recvMessage()
  33. charrecvBuf[1024];
  34. intret=0;
  35. while(true)
  36. ret=recv(_socektClient,recvBuf,153); font-weight:bold; background-color:inherit">sizeof(recvBuf),0);
  37. if(ret<0)
  38. log("recverror");
  39. break;
  40. if(ret>0&&onRecv!=nullptr)
  41. onRecv(recvBuf,ret);
  42. _mutex.lock();
  43. if(onDisconnect!=nullptr)
  44. onDisconnect();
  45. voidSocketClient::sendMessage(intcount)
  46. if(_socektClient!=0)
  47. intret=send(_socektClient,data,count,0);
  48. log("senderror!");
  49. }
原文链接:https://www.f2er.com/cocos2dx/345113.html

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