GraphQL Subscriptions를 활용한 자바스크립트 실시간 게임 서버 구축하기

서론

실시간 게임 서버를 구축할 때는 실시간 데이터 업데이트가 중요합니다. 이를 위해 GraphQL Subscriptions를 사용하여 자바스크립트로 실시간 게임 서버를 구축하는 방법을 알아보겠습니다.

GraphQL Subscriptions란?

GraphQL Subscriptions는 GraphQL의 일부인데, 이를 사용하면 클라이언트에서 서버로 데이터를 구독하고 업데이트할 수 있습니다. 이는 웹소켓 프로토콜을 기반으로 동작하며, 서버에서 데이터의 변경이 발생할 때마다 클라이언트에 실시간으로 업데이트된 데이터를 전송할 수 있습니다.

실시간 게임 서버 구축하기

  1. Node.js와 Express를 사용하여 GraphQL 서버를 구축합니다.
  2. Apollo Server를 설치합니다.
    npm install apollo-server
    
  3. GraphQL 스키마를 정의합니다. ```javascript const typeDefs = ` type Game { id: ID! name: String! score: Int! }

type Query { game(id: ID!): Game games: [Game] }

type Mutation { createGame(name: String!, score: Int!): Game updateScore(id: ID!, score: Int!): Game }

type Subscription { gameUpdated: Game } `;

4. resolvers를 작성합니다.
```javascript
const resolvers = {
  Query: {
    game: (parent, { id }) => {
      // 게임 정보 반환 로직 구현
    },
    games: () => {
      // 게임 목록 반환 로직 구현
    },
  },
  Mutation: {
    createGame: (parent, { name, score }) => {
      // 게임 생성 로직 구현
    },
    updateScore: (parent, { id, score }) => {
      // 점수 업데이트 로직 구현
    },
  },
  Subscription: {
    gameUpdated: {
      resolve: (parent) => {
        return parent;
      },
      subscribe: () => pubsub.asyncIterator('GAME_UPDATED'),
    },
  },
};
  1. Apollo Server를 시작합니다. ```javascript import { ApolloServer } from ‘apollo-server-express’;

const server = new ApolloServer({ typeDefs, resolvers, });

server.applyMiddleware({ app }); httpServer.listen(4000, () => { console.log(🚀 Server ready at http://localhost:4000${server.graphqlPath}) });

6. 클라이언트에서 GraphQL Subscriptions를 구독하고 업데이트된 데이터를 받아옵니다.
```javascript
import { ApolloClient, InMemoryCache, gql } from '@apollo/client';
import { SubscriptionClient } from 'subscriptions-transport-ws';
import { WebSocketLink } from '@apollo/client/link/ws';

const subscriptionClient = new SubscriptionClient('ws://localhost:4000/graphql', {
  reconnect: true,
});

const wsLink = new WebSocketLink(subscriptionClient);

const client = new ApolloClient({
  link: wsLink,
  cache: new InMemoryCache(),
});

client.subscribe({
  query: gql`
    subscription {
      gameUpdated {
        id
        name
        score
      }
    }
  `,
}).subscribe({
  next(data) {
    console.log(data);
    // 업데이트된 게임 데이터 처리 로직 구현
  },
  error(error) {
    console.error(error);
  },
});

마무리

GraphQL Subscriptions를 사용하여 자바스크립트로 실시간 게임 서버를 구축하는 방법을 알아보았습니다. 이를 통해 게임 서버에서 발생하는 데이터의 실시간 업데이트를 클라이언트에서 간편하게 처리할 수 있습니다.

#graphql #javascript