> For the complete documentation index, see [llms.txt](https://docs.decentraland.org/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.decentraland.org/creator/content-creator-ko/sdk7/networking/network-connections.md). Agents can also search and read this documentation through its [MCP server](https://docs.decentraland.org/~gitbook/mcp).

# 네트워크 연결

씬을 외부 서버 및 API와 통신하는 방법.

장면에서 API를 제공하는 외부 서비스를 활용할 수 있습니다. 이를 통해 최신 가격 데이터, 날씨 데이터 또는 API에서 제공하는 다른 종류의 정보를 가져올 수 있습니다.

장면을 지원하고 플레이어 간 데이터를 동기화하는 자체 외부 서버를 설정할 수도 있습니다. REST API를 제공하는 서버나 WebSocket을 사용하는 서버를 이용하면 됩니다.

## REST API 호출

장면의 코드는 REST API를 호출해 데이터를 가져올 수 있습니다.

서버가 응답을 보내는 데 시간이 걸릴 수 있으므로, 이 명령은 다음을 사용하는 [비동기 함수](https://docs.decentraland.org/creator/content-creator-ko/sdk7/programming-patterns/async-functions.md)로 실행해야 합니다. `executeTask()`.

```ts
executeTask(async () => {
	try {
		let response = await fetch(callUrl)
		let json = await response.json()
		console.log(json)
	} catch {
		console.log('failed to reach URL')
	}
})
```

fetch 명령에는 헤더, HTTP 메서드, HTTP 본문을 하나의 객체에 묶어 전달하는 두 번째 선택적 인수를 포함할 수도 있습니다.

* **url**: 요청을 보낼 주소
* **init**: 다음을 포함할 수 있는 `RequestInit` 객체:
  * **method** : 사용할 HTTP 메서드(GET, POST, DELETE 등)
  * **body**: 요청 본문의 내용입니다. 문자열로 변환한 JSON 객체로 보내야 합니다.
  * **headers**: 요청에 포함할 추가 헤더입니다.
  * **redirect**: 리디렉션 전략('follow' | 'error' | 'manual')
  * **timeout**: 요청이 실패하기 전에 응답을 기다리는 시간입니다. 기본값은 30000밀리초(30초)입니다.

```ts
executeTask(async () => {
	try {
		let response = await fetch(callUrl, {
			headers: { 'Content-Type': 'application/json' },
			method: 'POST',
			body: JSON.stringify(myBody),
		})
		let json = await response.json()
		console.log(json)
	} catch {
		console.log('failed to reach URL')
	}
})
```

fetch 명령은 다음 데이터가 포함된 `response` 객체를 반환합니다.

* `headers`: `ReadOnlyHeaders` 객체입니다. 특정 헤더를 가져오려면 `get()` 메서드를 호출하고, 헤더가 있는지 확인하려면 `has()` 메서드를 호출합니다.
* `ok`: 불리언
* `redirected`: 불리언
* `status`: 상태 코드 번호
* `statusText`: 상태 코드의 텍스트
* `type`: 다음 값 중 하나입니다: *basic*, *cors*, *default*, *error*, *opaque*, *opaqueredirect*
* `url`: 전송된 URL
* `json()`: 본문을 JSON 형식으로 가져옵니다.
* `text()`: 본문을 텍스트로 가져옵니다.

{% hint style="warning" %}
**📔 참고**: `json()` 및 `text()` 는 함께 사용할 수 없습니다. 응답 본문을 두 형식 중 하나로 가져오면 다른 형식으로는 더 이상 가져올 수 없습니다.  `response` 객체에서 말입니다.
{% endhint %}

{% hint style="warning" %}
**📔 참고**: 각 Decentraland 씬은 한 번에 하나의 `fetch` 명령만 실행할 수 있습니다. 요청은 내부적으로 대기열에 추가되므로 씬 코드의 구조에는 영향을 주지 않습니다. 씬에서 서로 다른 엔드포인트로 여러 요청을 보내야 한다면, 각 요청은 이전 요청에 대한 응답이 도착한 후에만 전송된다는 점에 유의하세요.
{% endhint %}

## 서명된 요청

요청이 Decentraland 내 플레이어 세션에서 발생했음을 확인하는 추가 보안 조치를 적용할 수 있습니다. Decentraland 세션이 각 플레이어의 주소를 기반으로 플레이어마다 생성하는 임시 키로 서명한 추가 서명을 요청에 포함해 전송하면 됩니다. 요청을 받는 서버는 서명된 메시지가 현재 월드 내에서 활성 상태인 주소와 일치하는지 확인할 수 있습니다.

이러한 보안 조치는 플레이어가 게임에서 토큰이나 포인트를 파밍하는 등 시스템을 악용할 유인이 있을 수 있는 경우 특히 유용합니다.

서명된 요청을 보내려면 `signedFetch()` 함수를 사용하면 됩니다. 사용 방법은 `fetch()` 함수를 사용하는 방법과 정확히 같습니다.

```ts
import { signedFetch } from '~system/SignedFetch'

executeTask(async () => {
	try {
		let response = await signedFetch({
			url: callUrl,
			init: {
				headers: { 'Content-Type': 'application/json' },
				method: 'POST',
				body: JSON.stringify(myBody),
			},
		})

		if (!response.ok) {
			throw new Error('Invalid response')
		}

		let json = JSON.parse(response.body)

		console.log('Response received: ', json)
	} catch {
		console.log('failed to reach URL')
	}
})
```

요청에는 서명된 메시지와 이를 해석하기 위한 메타데이터가 포함된 추가 헤더가 들어갑니다. 서명된 메시지는 플레이어의 임시 키를 사용해 암호화한 요청의 모든 내용으로 구성됩니다.

&#x20;`signedFetch()` 은 `fetch()` 함수와 달리 응답이 전체 HTTP 메시지의 Promise이며, 다음과 같이 표현됩니다. `FlatFetchResponse` 객체입니다. 여기에는 다음 속성이 포함됩니다.

* `body`
* `headers`
* `ok`
* `status`
* `statusText`

이 **본문은** 항상 문자열이며, 위 예시와 같이 파싱할 수 있습니다.

### 서명된 요청 검증

서명된 요청을 사용하려면 요청을 받는 서버에서 서명이 요청의 나머지 내용과 일치하는지, 그리고 서명된 메시지에 인코딩된 타임스탬프가 현재 시각과 일치하는지 검증해야 합니다.

이 작업을 수행하는 서버의 간단한 예시는 다음 예제 씬에서 확인할 수 있습니다.

[플레이어 진위 검증](https://github.com/decentraland-scenes/validate-player-authenticity)

## 요청 시간 초과

HTTP 요청이 응답을 받기까지 너무 오래 걸리면 실패 처리되어 다른 요청을 보낼 수 있습니다.  `fetch()`의 기본 시간 초과 임계값은 30초이지만,  `timeout` 속성을 설정하여 각 요청에 다른 값을 지정할 수 있습니다. 이 값의 단위는 밀리초입니다. `timeout` 밀리초 단위로 지정합니다.

```ts
fetch('https://some-url.com', { timeout: 1000 })
```

## WebSocket 사용

WebSocket 서버가 보안 연결을 사용하는 경우 데이터를 보내고 받을 수도 있습니다. 보안 연결은  *wss*.

```ts
var socket = new WebSocket('url')

socket.onmessage = function (event) {
	console.log('WebSocket message received:', event)
}
```

WebSocket 사용 문법은 JavaScript에서 기본으로 제공하는 문법과 다르지 않습니다. WebSocket을 통해 메시지를 수신하고 전송하는 방법은  [Mozilla Web API](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) 문서에서 자세히 알아보세요.

{% hint style="info" %}
**💡 팁**: WebSocket 연결을 간편하게 사용할 수 있으며 Decentraland와 매우 잘 호환되는 것으로 검증된 라이브러리로는  [Colyseus](https://colyseus.io/)가 있습니다. 다른 여러 WebSocket 라이브러리는 Decentraland SDK와 호환되지 않습니다.

이 라이브러리는 WebSocket 연결 위에 추상화 계층을 구축하여 변경 사항에 쉽게 반응하고 서버에 일관된 게임 상태를 원격으로 저장할 수 있게 해 줍니다. 다음 예시에서 실제 작동 모습을 확인할 수 있습니다.

* [Cube Jumper](https://github.com/decentraland-scenes/cube-jumper-colyesus-sdk7)
* [Space Traitor](https://github.com/decentraland-scenes/Space-Traitor)
* [AI NPC](https://github.com/decentraland-scenes/inworld-ai-sdk7)
  {% endhint %}

## 네트워크 요청 디버깅

Debug Panel을 열어 네트워크 요청을 디버깅할 수 있습니다.

Debug Panel을 열려면 오른쪽 상단의  ![](https://3980763956-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoPnXBby9S6MrsW83Y9qZ%2Fuploads%2Fgit-blob-9af92d7a9edeb4111484adc136865c46bf27e9e1%2Fdebug-icon.webp?alt=media) 아이콘을 클릭합니다. 그런 다음  **Web Requests** 탭을 선택하고  **Open Chrome Devtools**.

를 클릭합니다. 그러면 Network 탭이 열린 새 Chrome 창이 표시됩니다.

자세한 내용은  [미리 보기에서 디버깅](https://docs.decentraland.org/creator/content-creator-ko/sdk7/debugging/debug-in-preview.md#web-requests) 을 참고하세요.


---

# 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 by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.decentraland.org/creator/content-creator-ko/sdk7/networking/network-connections.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
