WebSocket
WebSocket 是 HTML5 开始提供的一种浏览器与服务器间进行全双工通讯的网络技术。在 WebSocket API 中,浏览器和服务器只需要做一个握手的动作,然后,浏览器和服务器之间就形成了一条快速通道。两者之间就直接可以数据互相传送。
在cocos2d 中使用 WebSocket 与服务端通信非常简单
1. 继承WebSocket::Delegate并实现onOpen,onMessage,onClose和onError四个虚函数;
2. 创建WebSocket;
3. 初始化WebSocket(相当于链接服务器);
4. 发送数据;
5. 关闭WebSocket。
首先要引入相关库和使用相关命名空间
#include "network/WebSocket.h"
using namespace cocos2d::network;
继承 WebSocket::Delegate
class HelloWorld : public cocos2d::Layer,public WebSocket::Delegate
实现四个虚函数
void HelloWorld::onOpen(WebSocket * ws)
{
m_log_text->setString("web socket connect success!");
}
void HelloWorld::onMessage(WebSocket * ws, const WebSocket::Data & data)
{
if (data.isBinary)
{
std::string str;
for (int i = 0; i < data.len; i++)
{
str += (data.bytes[i]);
}
m_log_text->setString(str);
}
else
{
char str[256];
sprintf(str, "%s", data.bytes);
m_log_text->setString(str);
}
}
void HelloWorld::onClose(WebSocket * ws)
{
m_log_text->setString("WebSocket has been closed!");
m_wSocket = nullptr;
CC_SAFE_DELETE(ws);
}
void HelloWorld::onError(WebSocket * ws, const WebSocket::ErrorCode & errorCode)
{
char str[256];
sprintf(str, "error code:%d", errorCode);
m_log_text->setString(str);
}
创建Socket、初始化Socket
void HelloWorld::onOpenBtnClick(Ref * pRef)
{
if (m_wSocket == NULL)
{
//创建WebSocket
m_wSocket = new WebSocket();
//初始化WebSocket,这一步会链接服务器
m_wSocket->init(*this, "ws://echo.websocket.org");
}
}
发送消息
void HelloWorld::onSendTxtBtnClick(Ref * pRef)
{
//发送文本消息
if (m_wSocket)
{
static int inx = 1;
char str[256];
sprintf(str, "hello world! :with text :No %d", inx++);
m_wSocket->send(str);
}
}
void HelloWorld::onSendBinBtnClick(Ref * pRef)
{
//发送二进制消息
if (m_wSocket)
{
static int inx = 1;
char str[256];
sprintf(str, "hello world! :with binary :No %d", inx++);
m_wSocket->send((unsigned char*)str, sizeof(str));
}
}
关闭Socket
void HelloWorld::onCloseBtnClick(Ref * pRef)
{
//关闭WebSocket
if (m_wSocket)
{
m_wSocket->close();
}
}