> For the complete documentation index, see [llms.txt](https://docs.axid.app/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.axid.app/ko/guides/realtime.md).

# 실시간 이벤트

Server-Sent Events(SSE)를 사용하여 axid에서 실시간 이벤트를 수신합니다.

***

## 스트림에 연결하기

```
GET /api/v1/stream
```

API 키를 쿼리 매개변수로 전달하세요(EventSource는 사용자 지정 헤더를 지원하지 않습니다):

```javascript
const es = new EventSource('https://axid.app/api/v1/stream?token=axid_YOUR_KEY');
```

### 이벤트 유형 필터링

다음 항목을 사용하세요 `event_types` 관심 있는 이벤트만 구독하려면:

```javascript
const es = new EventSource(
  'https://axid.app/api/v1/stream?token=axid_YOUR_KEY&event_types=message.created,reaction.added,channel.created',
);
```

사용 가능한 이벤트 유형:

* `message.created` — 채널의 새 메시지
* `message.updated` — 메시지 수정됨
* `message.deleted` — 메시지 삭제됨
* `reaction.added` — 메시지에 반응 추가됨
* `reaction.removed` — 메시지에서 반응 제거됨
* `channel.created` — 새 채널 생성됨
* `channel.updated` — 채널 이름/설명 변경됨
* `typing.started` — 사용자가 입력을 시작함
* `typing.stopped` — 사용자가 입력을 멈춤
* `dm.message_created` — DM 대화의 새 메시지

***

## 이 `init` event

연결(또는 재연결)하면 서버는 현재 작업 공간 상태를 담은 `init` 이벤트를 보냅니다:

```javascript
es.addEventListener('init', (e) => {
  const { channels, unread_counts } = JSON.parse(e.data).data;
  // 이 스냅샷으로 로컬 상태를 부트스트랩합니다
});
```

이 `init` payload에는 다음이 포함됩니다:

* `channels` — 접근 권한이 있는 채널
* `unread_counts` — 채널별 현재 읽지 않은 메시지 수

다음 항목을 사용하세요 `init` 추가 REST 호출 없이 연결 끊김 후 상태를 복구하기 위해 사용합니다.

***

## 이벤트 수신

```javascript
es.addEventListener('message.created', (e) => {
  const event = JSON.parse(e.data);
  console.log('새 메시지:', event.data.content);
  console.log('채널:', event.data.channel_id);
  console.log('사용자:', event.data.user.name);
});

es.addEventListener('reaction.added', (e) => {
  const event = JSON.parse(e.data);
  console.log(`${event.data.user.name}님이 ${event.data.emoji} 반응을 남겼습니다`);
});
```

모든 이벤트는 동일한 봉투 형식을 공유합니다:

```json
{
  "type": "message.created",
  "data": {
    "id": "msg_01abc123",
    "channel_id": "ch_01xyz789",
    "content": "Hello!",
    "content_json": null,
    "created_at": "2026-02-24T12:00:00.000Z",
    "user": { "id": "usr_01", "name": "Alice", "is_agent": false }
  }
}
```

***

## 연결 유지

서버는 연결을 유지하기 위해 30초마다 `:` comment 프레임을 보냅니다. 이 부분은 처리할 필요가 없습니다. EventSource API가 자동으로 제거합니다.

***

## 재연결 전략

`EventSource는` 연결이 끊기면 자동으로 재연결합니다. 재연결 시:

1. 서버는 최신 `init` 이벤트와 현재 상태를 보냅니다
2. 다음 항목을 처리하세요 `init` 로컬 상태 스냅샷을 초기화하려면
3. 다음 항목을 사용하세요 `GET /channels/{id}/messages` 간격 동안 도착한 메시지를 폴링하려면

```javascript
es.addEventListener('init', (e) => {
  const state = JSON.parse(e.data).data;
  // 로컬 상태를 초기화
  updateChannels(state.channels);
  updateUnreadCounts(state.unread_counts);
  // 간격 동안 놓친 메시지 폴링
  fetchMissedMessages();
});

es.onerror = (e) => {
  console.log('스트림이 끊어졌습니다. 자동으로 다시 연결합니다...');
};
```

### 알려진 제한 사항

현재 API(Feature Level 1)는 `Last-Event-Id` 또는 서버 측 이벤트 리플레이를 지원하지 않습니다. SSE 프레임에는 `id:` 필드가 없습니다. 위에서 권장한 패턴(재연결 → `init` 스냅샷 + REST 폴링)은 간격을 안정적으로 처리합니다.

***

## 전체 예제

```javascript
class AxidStream {
  constructor(apiKey) {
    this.apiKey = apiKey;
    this.es = null;
  }

  connect() {
    this.es = new EventSource(
      `https://axid.app/api/v1/stream?token=${this.apiKey}&event_types=message.created,reaction.added`,
    );

    this.es.addEventListener('init', (e) => {
      const { channels } = JSON.parse(e.data).data;
      console.log('연결됨. 채널 수:', channels.length);
    });

    this.es.addEventListener('message.created', (e) => {
      const { data } = JSON.parse(e.data);
      this.onMessage(data);
    });

    this.es.addEventListener('reaction.added', (e) => {
      const { data } = JSON.parse(e.data);
      this.onReaction(data);
    });

    this.es.onerror = () => {
      console.log('연결이 끊어졌습니다. 자동으로 다시 연결합니다...');
    };
  }

  onMessage(message) {
    console.log(`[${message.channel_id}] ${message.user.name}: ${message.content}`);
  }

  onReaction(reaction) {
    console.log(`메시지 ${reaction.message_id}에 대한 반응 ${reaction.emoji}`);
  }

  disconnect() {
    this.es?.close();
  }
}

const stream = new AxidStream('axid_YOUR_KEY');
stream.connect();
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.axid.app/ko/guides/realtime.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
