티스토리 뷰

userInput.js
0.00MB

 

mocorgo.js
0.02MB

 

 조금 해메면서 같은 기능을 구현 해봐야 할듯 싶다. vite와 yarn을 쓸 생각이라 yarn create vite를 해준다. 

 

 일단 자바스크립트 게임 엔진 부분을 코드에 추가해 준다. 

{
  "name": "socketgame",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview"
  },
  "devDependencies": {
    "vite": "^5.4.1",
    "express": "^4.19.2",
    "vite-express": "^0.18.0",
    "socket.io": "^4.7.5"
  }
}

 기본 세팅은 이걸로 간다. yarn을 하면 의존성 설치를 하고 yarn dev를 하면 실행을 한다. VS code 확장 프로그램에서 live server를 설치해 주면 조금 편하게 작업을 할수가 있다.  

 

 

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
    #canvas{
      border:  1px solid black;
      display: block;
      margin: 0 auto;
      background: #fffacc;
    }
  </style>
  <title>Document</title>
</head>
<body>
  <canvas id = "canvas" tabindex="0" width="640" height="480"></canvas>
  <script type="module" src="client.js"></script> 
</body>
</html>

 

 기본 세팅 캔버스는 이렇게 한다. 캔버스 말고 CSS라든지 이런게 꽤 다룰게 많긴 한데 그거 배우는 건 뒤로 미루자. 일단 canvas 원툴로 간다.

 

 처음 프로그래밍을 배운게 웹 게임 만들기 교양 수업이였는데 그때도 canvas이외엔 딱히 다루어 적이 없다. 

 

let canvas;
let context; 

if (typeof document !== 'undefined') {
    canvas = document.getElementById('canvas');
    context = canvas.getContext('2d');
}

 

 서버에서 구동하는 프로그램은 렌더링을 할 이유가 없기 때문에 이런식으로 구현을 해준다. 유니티도 마찬가지인데 리눅스 데디케이트 서버 버전이 따로 있다. 서버 버전은 음원이라든지 이런것도 필요 없기 때문에 리소스의 경우에도 따로 최적화된 버전을 만들어줘야 한다. 

 

 게임 자체를 서버에서 돌아가게 하고 클라이언트는 결과값만 받아서 렌더링 되게 하는 식이다. 그래서 게임 서버의 경우에는 꽤나 복잡한 편이다. 

 

  한번에 진행을 하면 힘이 들기 때문에 일단 서버를 키고 클라이언트에서 접속하면 a user connected를 출력하는 것부터 만들자. node server를 치면 서버를 킬수가 있다. 

 

 

server.js 코드는 이렇고 

 

import { Server } from "socket.io";
import express from "express";
import * as http from "http";
import ViteExpress from "vite-express";
import cors from "cors";

const PORT = 3000;

const app = express();
app.use(cors());
const server = http.createServer(app);
const io = new Server(server, {
    cors: {
        origin: "http://127.0.0.1:5500",
        methods: ["GET", "POST"]
      }
});

server.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

io.on('connect', (socket) => {
    console.log("A user connected!");
   
    socket.on('disconnect', () => {
        console.log('A user disconnected');
      });
});

 

client.js 코드는 이렇다. 

 

import { io } from "https://cdn.socket.io/4.7.5/socket.io.esm.min.js";

const PORT = 3000;

const socket = io('http://localhost:' + PORT);
const canvas = document.getElementById('canvas');
const context = canvas.getContext('2d');

socket.on('connect', (server) => {
    console.log("Connected to server!");
   
});

socket.on('disconnect', () => {
    console.log('Disconnected from server');
});

 

저기 라이브러리를 링크를 불러오게 해 두었는데 그냥 로컬에서 불러오면 안되나 싶긴하다. 그렇게 해서 되나 확인해보자. 

...

...

...

 잘 안된다 그냥 이렇게 가도록 한다. 

 

 그 다음에 해야 할것이 메세지를 보내고 받는 거다. emit을 쓰면 된다고 한다. 서버가 모든 클라이언트에 쏴주는 거는 broadcast일꺼다. alert을 써서 클라이언트가 접속할때마다 새로운 클라이언트가 접속했다는 걸 알려주는 걸 만들도록 한다. 

 

 이거가 끝나면 캐릭터를 클라이언트에서 움직이는 걸 구현 해본다. 그다음에 해야 할께 게임 메카니즘 자체는 서버에서 구동하도록 하고 각 클라이언트에게는 렌더만 알려주는 거다. 해당 게임 엔진에 렌더 온니 함수가 있기 때문에 이걸 쓰면 된다. 

 

클라이언트

socket.emit('sayToServer', "Hi, there!");
socket.on('sayToClient', message => {
    alert(message);
});

 

서버 

io.on('connect', (socket) => {
    console.log("A user connected!");

    socket.on('sayToServer', (message) => {
        socket.broadcast.emit('sayToClient', socket.id + ": " + message);
    });
    
    socket.on('disconnect', () => {
        console.log('A user disconnected');
    });
});

 서버에서는 받은 메세지를 다시 보내주도록 하자. 정상적으로 작동하는지 확인해 보자. 

 

 정상적으로 작동한다. Socket.io 사용법은 이게 기본이고 이제 게임 서버를 만들어 보는걸로 끝을 내야 겠다. 

 

서버

import { Server } from "socket.io";
import express from "express";
import * as http from "http";
import ViteExpress from "vite-express";
import cors from "cors";

const PORT = 3000;

const app = express();
app.use(cors());
const server = http.createServer(app);
const io = new Server(server, {
  cors: {
    origin: "http://127.0.0.1:5500",
    methods: ["GET", "POST"]
  }
});

server.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

io.on('connect', socket => {
  console.log("A user connected!");

  socket.on('sayToServer', message => {
    console.log(message);
    const say = socket.id + ": " + message;
    socket.broadcast.emit('sayToClient', say);
  });
 
  socket.on('disconnect', () => {
     console.log('A user disconnected');
  });
});
 
 
클라이언트 
 

const PORT = 3000;

const socket = io('http://localhost:' + PORT);
const canvas = document.getElementById('canvas');
const context = canvas.getContext('2d');

socket.on('connect', () => {
  console.log("Connected to server!");
});

socket.emit('sayToServer', "Hi, there!");
socket.on('sayToClient', message => {
  alert(message);
});

socket.on('disconnect', () => {
  console.log('Disconnected from server');
});

 

'학습 > AWS' 카테고리의 다른 글

서너번 반복해 보고  (0) 2024.08.22
웹 게임 서버 만들어 보기  (1) 2024.08.21
제한된 범위를 반복해야  (0) 2024.08.20
접근성 높은 메타버스려면  (0) 2024.08.19
Socket IO 연구  (0) 2024.08.18