> 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-zh/chang-jing-sdk7/lian-wang/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 的服务器，也可以使用采用 WebSockets 的服务器。

## 调用 REST API

场景代码可以向 REST API 发送请求以获取数据。

由于服务器可能需要一些时间才能返回响应，因此必须将此命令作为 [异步函数](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/bian-cheng-mo-shi/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')
	}
})
```

请求会附带一组额外的标头，其中包含签名消息和用于解读该消息的一组元数据。签名消息由使用玩家临时密钥加密的请求全部内容组成。

signedFetch() `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 原生实现没有区别。请参阅 [Mozilla Web API](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) 文档，了解如何通过 WebSocket 接收和发送消息。

{% hint style="info" %}
**💡 提示**：有一个简化 WebSocket 连接使用的库，已被证明与 Decentraland 配合良好，那就是 [Colyseus](https://colyseus.io/)。其他一些 WebSocket 库与 Decentraland SDK 不兼容。

它在 WebSocket 连接之上构建了一层抽象，使你能够轻松响应变化，并在服务器上远程存储一致的游戏状态。你可以在以下示例中查看实际效果：

* [方块跳跃](https://github.com/decentraland-scenes/cube-jumper-colyesus-sdk7)
* [太空叛徒](https://github.com/decentraland-scenes/Space-Traitor)
* [AI NPC](https://github.com/decentraland-scenes/inworld-ai-sdk7)
  {% endhint %}

## 调试网络请求

你可以打开调试面板来调试网络请求。

要打开调试面板，请点击右上角的 ![](https://2460066822-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoPnXBby9S6MrsW83Y9qZ%2Fuploads%2Fgit-blob-9af92d7a9edeb4111484adc136865c46bf27e9e1%2Fdebug-icon.webp?alt=media) 图标，然后选择 **Web 请求** 选项卡，并点击 **打开 Chrome 开发者工具**.

这会打开一个新的 Chrome 窗口，并显示“网络”选项卡。

更多详情请参阅 [在预览中调试](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/tiao-shi/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-zh/chang-jing-sdk7/lian-wang/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.
