0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【14日目】25日間でCocos Creatorでゲームを作る

0
Posted at

PacketTypeを定数に切り分ける

PacketTypeとは

this.socket.emit('login_request', { username: username });login_requestの部分のことを指し、通信データの種類を表すもの。
定数で定義しておくのがベター。

Cocos側の定義ファイルを作成する

  1. assets/scripts内にPacketType.tsを作成する
  2. 追記する
export enum PacketType {
  LOGIN_REQUEST = 'login_request',
  LOGIN_RESPONSE = 'login_response',
}
  1. NetworkManager.tsを書き換える
NetworkManager.ts
import { _decorator, Component, log } from 'cc';
import io from 'socket.io-client/dist/socket.io.js';

import { PacketType } from './PacketType'; // 追記
NetworkManager.ts
this.socket.on(PacketType.LOGIN_RESPONSE, (data) => {
    log('サーバーからの返事:', data);
    // LoginUIに結果を伝える(イベント通知)
    this.node.emit('on_login_finished', data);
});
NetworkManager.ts
this.socket.emit(PacketType.LOGIN_REQUEST, { username: username });

サーバー側の定義ファイルを作成する

  1. game-serverにPacketType.tsを作成する
  2. 追記する
const PacketType = {
  LOGIN_REQUEST: "login_request",
  LOGIN_RESPONSE: "login_response",
};

module.exports = PacketType;
  1. index.jsを修正する
index.js
const express = require("express");
const http = require("http");
const { Server } = require("socket.io");
const PacketType = require('./PacketType'); // 追記
index.js
socket.on(PacketType.LOGIN_REQUEST, (data) => {
index.js
socket.emit(PacketType.LOGIN_RESPONSE, {

※エラー時と2箇所あり

動作確認をする

  1. ターミナルでサーバーのプロセスが起動中の場合、Ctrl + Cで停止させる
  2. サイドプロセスを起動する
    node index.js
  3. Cocos CreatorでMenuSceneを立ち上げユーザー情報を送信する
    image.png

まとめ

これで今後もパケットが増えた時も管理が行いやすくなりました。
また、PacketTypeを見るだけで大まかな通信仕様の把握も行いやすくなります。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?