とあるプログラマの備忘録

都内某所に住むプログラマが自分用に備忘録を残すという趣旨のブログです。はてなダイアリーから移動しました!

Cocos2dx 3.0 WebSocket通信してみる

前にUnityでWebSocket通信のテストを行っていたのですが、 その際に使用していたWebSocketServerにCocos2xから接続できるかやってみようと思います。

サンプルソースのご使用は自己責任でお願いいたします。

Title.h

#ifndef __TITLE_SCENE_H__
#define __TITLE_SCENE_H__

#include "cocos2d.h"
#include <WebSocket.h>

USING_NS_CC;
using namespace network;

class Title : public Layer, WebSocket::Delegate
{
    //webSocket
    WebSocket* websocket;
    
public:
    static Scene* createScene();
    virtual bool init();
    Title();
    CREATE_FUNC(Title);
    Size window_size;
    LabelTTF* status;

    void loadWebSocket();
    
    //webSocket
    virtual void onOpen(WebSocket* ws);
    virtual void onMessage(WebSocket* ws, const WebSocket::Data& data);
    virtual void onClose(WebSocket* ws);
    virtual void onError(WebSocket* ws, const WebSocket::ErrorCode& error);
    void sendMessage(float dt);
};

#endif // __TITLE_SCENE_H__

Title.cpp

#include "Title.h"

//コンストラクタ
Title::Title()
{
    if (websocket) websocket->close();
}

Scene* Title::createScene()
{
    auto scene = Scene::create();
    auto layer = Title::create();
    scene->addChild(layer);
    return scene;
}

// on "init" you need to initialize your instance
bool Title::init()
{
    if ( !Layer::init() )
    {
        return false;
    }

    //ステータスラベルの作成    
    window_size = Director::getInstance()->getWinSize();
    status = LabelTTF::create("In connection...", "Arial", 15);
    status->setPosition(Point(window_size.width / 2 , window_size.height / 2));
    this->addChild(status);

    this->loadWebSocket();
    
    return true;
}

void Title::loadWebSocket()
{
    websocket = new WebSocket();

    // ドメインとポートは自分のサーバーに合わせる
    websocket->init(*this, "ws://domain.com:8080/echo");
}

void Title::onOpen(WebSocket* ws)
{
    status->setString("Successful connection");
    scheduleOnce(schedule_selector(Title::sendMessage), 1.0f);
}

void Title::onMessage(WebSocket* ws, const WebSocket::Data& data)
{
    auto *text = String::createWithFormat("%s", data.bytes);
    status->setString(text->getCString());
}

void Title::onClose(WebSocket* ws)
{
    websocket = nullptr;
    status->setString("Closed connection");
}

void Title::onError(WebSocket* ws, const WebSocket::ErrorCode& error)
{
    char buf[100] = {0};
    sprintf(buf, "Error code: %d", error);
    status->setString(buf);
}

void Title::sendMessage(float dt)
{
    if (websocket->getReadyState() == WebSocket::State::OPEN){
        status->setString("Send Message");
        websocket->send("こんにちわ、ラハルです");
    }
}

実行してみる

サーバー側

info: Wrench\ConnectionManager: Wrench\Connection: xxx.xxx.xxx.xxx:xxxx (0): Connected info: Wrench\ConnectionManager: Wrench\Connection: xxx.xxx.xxx.xxx:xxxx (0): Handshake successful: xxx.xxx.xxx.xxx:xxxx (0) connected to /echo debug: Wrench\ConnectionManager: Wrench\Connection: xxx.xxx.xxx.xxx:xxxx (0): Handling payload: こんにちわ、ラハルです

エミュレーター

f:id:raharu0425:20140505163312p:plain