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?

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

0
Posted at

Node.jsでゲームサーバーの環境を準備する

設計イメージ

前準備

NewProjectのディレクトリの直下にgame-serverのディレクトリを準備する

NewProject/ (全体のルート)
├── assets/
├── profiles/
├── scene-root/
│
└── game-server/

Node.jsをインストールする

  1. VS CodeでNewProjectを開き、ターミナルを起動する
  2. geme-serverのディレクトリへ移動する
    cd game-server
  3. Node.jsの初期化をする
    npm init -y
  4. 必要なライブラリのインストールをする
    npm install express socket.io

サーバー本体の実装をする

  1. game-server直下にindex.jsを作成する
  2. コードを記載する
indx.js
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');

const fs = require('fs');
const dbFile = 'db.json';
const initDb = () => {
    if (!fs.existsSync(dbFile)) {
        fs.writeFileSync(dbFile, JSON.stringify({ users: [] }, null, 2));
    }
};
initDb();

const app = express();
const server = http.createServer(app);
const io = new Server(server, { cors: { origin: "*" } });

io.on('connection', (socket) => {
    console.log('User connected:', socket.id);

    socket.on('login_request', (data) => {
        const username = data.username;
        
        const dbData = JSON.parse(fs.readFileSync(dbFile));
        
        let user = dbData.users.find(u => u.username === username);
        
        if (!user) {
            user = { username: username, level: 1, lastLogin: new Date() };
            dbData.users.push(user);

            fs.writeFileSync(dbFile, JSON.stringify(dbData, null, 2));
            console.log(`新規ユーザー登録: ${username}`);
        } else {
            console.log(`既存ユーザーログイン: ${username}`);
        }

        socket.emit('login_response', {
            success: true,
            userData: user
        });
    });
});

server.listen(3000, () => console.log('Server running on port 3000'));
  1. ターミナルでnode index.jsと入力する
  2. Server running on port 3000と表示されればOK
    また、初回起動時はdb.jsonも生成されます。
db.json
{
  "users": []
}

まとめ

これでサーバーの準備まで完了しました。
データを保持する方法として、本格的なDBを準備すると環境構築が大変になるので、今回はNode.js標準のfsモジュールを使って、JSON形式でデータを保持します。

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?