标签:
cocos2d-x官方没有封装原生socket,只提供了websocket,如果我们需要socket,不同团队有不同的造轮子的方案,其中使用Asio库的比较多,但是Asio库太过于庞大,我不太想用。其实只需要简单封装一下bsd socket就好了,几十行代码而已。
注意如果在android中测试,需要添加网络访问权限,而且不能在主线程中使用。
贴一发代码,只是简单测试了下,如果有问题再慢慢完善。
1 #ifndef __cpp_test__Socket__ 2 #define __cpp_test__Socket__ 3 4 #include <sys/socket.h> 5 #include <netinet/in.h> 6 7 typedef uint8_t byte; 8 typedef unsigned short ushort; 9 10 class Socket { 11 public: 12 Socket(); 13 Socket(int sockfd); 14 ~Socket(); 15 16 bool connect(const char* ip, ushort port); 17 bool listen(ushort port, int size); 18 Socket* accept(); 19 20 ssize_t send(byte* buffer, size_t size); 21 ssize_t recv(byte* buffer, size_t size); 22 23 private: 24 bool bind(ushort port); 25 26 int _sockfd; 27 struct sockaddr_in _addr_local; 28 }; 29 30 #endif /* defined(__cpp_test__Socket__) */
1 #include "Socket.h" 2 #include <netdb.h> 3 #include <unistd.h> 4 #include <arpa/inet.h> 5 #include <stdlib.h> 6 7 Socket::Socket() { 8 } 9 10 Socket::Socket(int sockfd) { 11 _sockfd = sockfd; 12 } 13 14 Socket::~Socket() { 15 close(_sockfd); 16 } 17 18 19 bool Socket::bind(ushort port) { 20 _addr_local.sin_family = AF_INET; 21 _addr_local.sin_addr.s_addr = INADDR_ANY; 22 _addr_local.sin_port = htons(port); 23 return ::bind(_sockfd, (struct sockaddr*)&_addr_local, sizeof(struct sockaddr)) == 0; 24 } 25 26 27 bool Socket::listen(ushort port, int size) { 28 _sockfd = socket(AF_INET, SOCK_STREAM, 0); 29 if(_sockfd < 0) { 30 return false; 31 } 32 33 this->bind(port); 34 return ::listen(_sockfd, size) == 0; 35 } 36 37 38 Socket* Socket::accept() { 39 struct sockaddr_in addr_remote; 40 socklen_t length = sizeof(addr_remote); 41 42 int remote = ::accept(_sockfd, (struct sockaddr*)&addr_remote, &length); 43 if(remote < 0) { 44 return nullptr; 45 } 46 return new Socket(remote); 47 } 48 49 50 bool Socket::connect(const char* ip, ushort port) { 51 this->bind(0); 52 53 struct sockaddr_in addr_remote; 54 addr_remote.sin_addr.s_addr = inet_addr(ip); 55 addr_remote.sin_family = AF_INET; 56 addr_remote.sin_port = htons(port); 57 58 int sockfd_remote = socket(addr_remote.sin_family, SOCK_STREAM, 0); 59 if(::connect(sockfd_remote, (sockaddr*)&addr_remote, sizeof(addr_remote)) < 0) { 60 close(sockfd_remote); 61 return false; 62 } 63 _sockfd = sockfd_remote; 64 return true; 65 } 66 67 68 ssize_t Socket::send(byte* buffer, size_t size) { 69 return ::send(_sockfd, buffer, size, 0); 70 } 71 72 73 ssize_t Socket::recv(byte* buffer, size_t size) { 74 return ::recv(_sockfd, buffer, size, 0); 75 }
bsd socket 简单封装。支持android、ios、mac osx
标签:
原文地址:http://www.cnblogs.com/wolfred7464/p/4828410.html