LoginSignup
2

More than 5 years have passed since last update.

【メモ・超初心者向け】CocosCreatorでWebSocketに接続する

Last updated at Posted at 2016-06-10

CocosCreatorでWebSocketに接続出来るか検証しました。
使用したのはHTML5で標準でついたWebSocketです。

tnakagawa様のいまさらHTML5 (WebSocket編)を参考にしています。

cc.Class({
    extends: cc.Component,

    properties: {
        // foo: {
        //    default: null,
        //    url: cc.Texture2D,  // optional, default is typeof default
        //    serializable: true, // optional, default is true
        //    visible: true,      // optional, default is true
        //    displayName: 'Foo', // optional
        //    readonly: false,    // optional, default is false
        // },
        // ...
    },

    // use this for initialization
    onLoad: function () {
        var uri = "ws://から始まるURIを記述";
        var webSocket = null;
        webSocket = new WebSocket(uri);
        webSocket.onopen = onOpen;
        webSocket.onmessage = onMessage;
        webSocket.onerror = onError;
        webSocket.onclose = onClose;

        // 接続イベント
        function onOpen(event) {
            console.log("接続しました。");
            var mes = "送信テスト";
            webSocket.send(mes);
        }

        // メッセージ受信イベント
        function onMessage(event) {
            console.log("受信しました");
            // ソケットを閉じる
            webSocket.close();
        }  

        // エラーイベント
        function onError(event) {
            console.log("エラーが発生しました。");
        }

        // 切断イベント
        function onClose(event) {
            console.log("切断しました。3秒後に再接続します。(" + event.code + ")");
            webSocket = null;
        }        

    },
});

接続した結果です。
コンソールログに表示しています。
結果.png

CROSの問題もありそうですが、ひとまず接続、送受信に成功しました。
注:Cocos Creator ver1.1.0で検証。今後やり方が変わる可能性が極めて高いです。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2