> For the complete documentation index, see [llms.txt](https://node1.gitbook.io/node1-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://node1.gitbook.io/node1-docs/documentation/zh/solana/tx-stream/tx-stream-receiving.md).

# 接收示例

在控制台配置目标公网 IPv4 与 UDP 端口，并确保防火墙允许接收。以下示例监听 `12000` 端口，请与订阅配置保持一致。

每个 UDP 包包含 **8 字节小端序 slot + bincode 序列化的 VersionedTransaction**。安装所选示例注释中的依赖后运行；收到日志中的 slot 和交易签名即可检查接收情况。如无数据，检查订阅状态、目标地址、端口和过滤条件。

## Rust

```rust
// Cargo.toml
// [dependencies]
// anyhow = "1"
// bincode = "1"
// solana-sdk = "2"
// tokio = { version = "1", features = ["macros", "net", "rt-multi-thread"] }

use anyhow::{Context, Result};
use solana_sdk::transaction::VersionedTransaction;
use tokio::net::UdpSocket;

#[tokio::main]
async fn main() -> Result<()> {
    let socket = UdpSocket::bind("0.0.0.0:12000").await?;
    let mut buffer = vec![0_u8; 65_535];

    println!("listening on 0.0.0.0:12000");

    loop {
        let (len, from) = socket.recv_from(&mut buffer).await?;
        let packet = &buffer[..len];
        if packet.len() < 8 {
            eprintln!("from={} udp_len={} error=packet too small for slot", from, len);
            continue;
        }

        let slot = u64::from_le_bytes(packet[..8].try_into().expect("slice length checked"));
        let payload = &packet[8..];

        match bincode::deserialize::<VersionedTransaction>(payload)
            .context("failed to decode VersionedTransaction")
        {
            Ok(tx) => {
                let sig = tx
                    .signatures
                    .first()
                    .map(|sig| sig.to_string())
                    .unwrap_or_else(|| "<none>".to_string());

                println!(
                    "from={} slot={} udp_len={} tx_len={} sig={}",
                    from,
                    slot,
                    len,
                    payload.len(),
                    sig,
                );
            }
            Err(error) => {
                eprintln!(
                    "from={} slot={} udp_len={} tx_len={} decode_error={:#}",
                    from,
                    slot,
                    len,
                    payload.len(),
                    error,
                );
            }
        }
    }
}
```

## Node.js

```javascript
// package.json
// {
//   "type": "module",
//   "dependencies": {
//     "@solana/web3.js": "^1"
//   }
// }

import dgram from 'node:dgram';
import { VersionedTransaction } from '@solana/web3.js';

const socket = dgram.createSocket('udp4');

socket.on('listening', () => {
  console.log('listening on 0.0.0.0:12000');
});

socket.on('message', (packet, remote) => {
  if (packet.length < 8) {
    console.error('packet too small for slot prefix');
    return;
  }

  try {
    const view = new DataView(packet.buffer, packet.byteOffset, packet.byteLength);
    const slot = view.getBigUint64(0, true);
    const payload = packet.subarray(8);
    const tx = VersionedTransaction.deserialize(payload);
    const sig = tx.signatures[0]
      ? Buffer.from(tx.signatures[0]).toString('base64')
      : 'none';

    console.log(
      'from=%s:%d slot=%s udp_len=%d tx_len=%d sig=%s',
      remote.address,
      remote.port,
      slot.toString(),
      packet.length,
      payload.length,
      sig,
    );
  } catch (error) {
    console.error('failed to decode tx packet', error);
  }
});

socket.bind(12000, '0.0.0.0');
```

## Python

```python
# requirements
# pip install solders

import socket
from solders.transaction import VersionedTransaction

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(("0.0.0.0", 12000))

print("listening on 0.0.0.0:12000")

while True:
    packet, addr = sock.recvfrom(65535)
    if len(packet) < 8:
        print(f"from={addr[0]}:{addr[1]} udp_len={len(packet)} error=packet too small for slot")
        continue

    slot = int.from_bytes(packet[:8], "little")
    payload = packet[8:]

    try:
        tx = VersionedTransaction.from_bytes(payload)
        sig = tx.signatures[0] if tx.signatures else "none"
        print(
            f"from={addr[0]}:{addr[1]} slot={slot} udp_len={len(packet)} tx_len={len(payload)} sig={sig}"
        )
    except Exception as error:
        print(
            f"from={addr[0]}:{addr[1]} slot={slot} udp_len={len(packet)} tx_len={len(payload)} decode_error={error}"
        )
```


---

# 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://node1.gitbook.io/node1-docs/documentation/zh/solana/tx-stream/tx-stream-receiving.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.
