> ## Documentation Index
> Fetch the complete documentation index at: https://docs.tenderly.co/llms.txt
> Use this file to discover all available pages before exploring further.

# 在 Virtual Environments 上连接到 WebSocket

> 通过 WebSocket 连接到 Virtual Environment，使用 eth_subscribe 和 eth_unsubscribe 获取实时的区块和事件更新。

WebSockets 提供高效的、与 Virtual Environments 的实时连接，允许在新区块和事件上立即更新。通过消除持续轮询的需要，WebSockets 降低了延迟和服务器负载。它们对于需要即时数据的 dapp（例如 DEX 和交易平台）至关重要。

Tenderly 支持 [Node RPCs](/node-rpc/overview) 和 [Virtual Environments](/virtual-environments/overview) 的 WebSocket，让您能够轻松构建和测试响应迅速、高性能的区块链应用程序。

使用 `eth_subscribe` 和 `eth_unsubscribe` 方法需要 WebSocket 访问权限。

* `eth_subscribe`
* `eth_unsubscribe`

## 连接到 Tenderly WebSockets

1. 前往 [Virtual Environments 页面](https://dashboard.tenderly.co/?redirectTo=testnets)
2. 创建一个新的 Virtual Environments 或选择一个现有的，并复制 RPC URL
3. 使用 `wscat` 测试：

```bash title="example" showLineNumbers theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
wscat -c wss://virtual.mainnet.rpc.tenderly.co/$VIRTUAL_TESTNET_ID
```

连接后，您可以向 Tenderly WebSocket 发送 JSON-RPC 请求。您将实时收到响应。例如，您可以尝试发送一个 **eth\_subscribe** 请求：

```json title="request.json" showLineNumbers theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
{"jsonrpc":"2.0","id":1,"method":"eth_subscribe","params":["newHeads"]}
```

您应该会收到类似以下的响应：

```json title="response.json" showLineNumbers theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
{"id":1,"jsonrpc":"2.0","result":"0x5ab4555c1620e384bfb27d9f3a01c71e"}
```
