cocos2dx socket 通信
来源:未知 责任编辑:责任编辑 发表时间:2014-01-06 18:19 点击:次
最近做一个联网实时交互的游戏,游戏中需要使用socket保持长连接,来保证客户端与服务器端进行实时交互。以下贴出自己的一些代码:
因为socket通信部分需要使用多线程,整个流程如下:
1、首先起一个线程,来进行socket通信的连接
int GameServer::connectThreadStart(){ // connect(GAMESERVER, CCString::create(GAMESERVER_PORT)->intValue()); int errCode = 0; do{ pthread_attr_t tAttr; errCode = pthread_attr_init(&tAttr); CC_BREAK_IF(errCode!=0); errCode = pthread_attr_setdetachstate(&tAttr, PTHREAD_CREATE_DETACHED); if (errCode!=0) { pthread_attr_destroy(&tAttr); break; } errCode = pthread_create(&m_gameThread, &tAttr, connectSocket, this); }while (0); return errCode; }
2、连接socket代码:
void* GameServer::connectSocket(void* args) { connect(192.168.1.2, 3343); return NULL; }
再此处进行socket连接,如果连接成功之后,将会通知主线程,连接已经成功,此处我们使用了cocos2dx高级开发教程中封装的MTNotificationQueue进行子线程向主线程的通信,如果你不了解,可以自己去百度
int GameServer::connect(const char* ip, unsigned int port) { CCLOG(Client begin connect IP: %s:%d ,ip,port); struct sockaddr_in sa; struct hostent* hp; hp = gethostbyname(ip); if(!hp){ return -1; } memset(&sa, 0, sizeof(sa)); memcpy((char*)&sa.sin_addr, hp->h_addr, hp->h_length); sa.sin_family = hp->h_addrtype; sa.sin_port = htons(port); m_socketHandle = socket(sa.sin_family, SOCK_STREAM, 0); if(m_socketHandle < 0){ printf( failed to create socket ); return -1; } if(::connect(m_socketHandle, (sockaddr*)&sa, sizeof(sa)) < 0){ printf( failed to connect socket ); ::close(m_socketHandle); return -1; } CCLOG(Client connect OK ! IP: %s:%d ,ip,port); MTNotificationQueue::sharedNotificationQueue()->postNotification(connectok, NULL); return 0; }
3、通知主线程之后,主线程将会负责开启新的线程进行recv监听,监听服务器下发的数据
void GameServer::initReceiveThread(CCObject* obj) { int errCode = 0; pthread_attr_t tAttr; errCode = pthread_attr_init(&tAttr); errCode = pthread_attr_setdetachstate(&tAttr, PTHREAD_CREATE_DETACHED); if (errCode!=0) { pthread_attr_destroy(&tAttr); }else{ errCode = pthread_create(&m_gameThread, &tAttr, listenSocketData, this); } if(errCode == 0){ CCLOG(Receive Thread OK!!!); }else{ CCLOG(Receive Thread Error!!!!); } MTNotificationQueue::sharedNotificationQueue()->postNotification(jointable, NULL); }
相关新闻>>
最新推荐更多>>>
- 发表评论
-
- 最新评论 更多>>
您可能感兴趣的文章
- Cocos2d-x初学指南(4): 生成animation 帧动画的2种方法
- PhoneGap API中文帮助文档——Device(设备)
- cocos2d-x-3.0 alpha1与C++11练习三:飞镖忍者,如何移动精灵及
- cocos2d-x Jni c++ java互调 并且相互刷新UI控件最简单例子(下
- Cocos2d-x--非布景层类和非布景层类的子类使用触摸
- AVAudioPlayer连续播放音乐的代码(通到单例)
- cocos2d-x编译安卓版本时实现“再按一次退出程序”的效果
- COCOS2D-X之骨骼动画武器换装效果Demo
- ReactiveCocoa (2) map,filter,fold
- cocos2dx 精灵的移动