# WebSocket Client

> 向 WebSocket 服务器发送消息。

Source: https://docs.sommatic.ai/zh/nodes/io.websocket/

- 标识: `io.websocket`
- 类别: 输入与输出
- 版本: 1.0.0
- 状态: 可用
- 执行方式: async

向 WebSocket 服务器发送消息。

## 配置

- `connection_id` (string, 必填): WebSocket 端点的凭据。接受 `api-key`、`basic-auth` 或 `object`（自定义握手请求头）类型的凭据。
- `message` (string, 必填): 要发送的消息
- `waitForResponse` (boolean, 可选): 默认值: `false`.

## 输出端口

- `out` (默认): 消息已发送或已收到响应
- `error`: 连接或传输错误

## 输入契约

- `connection_id` (string, 必填)
- `message` (string, 必填)
- `waitForResponse` (boolean, 可选)

## 输出契约

- `result` (string, 可选): 确认或响应

## 在表达式中

后续节点可通过 `$("WebSocket Client").item.json.<路径>` 读取此节点输出中的内容（请把 `WebSocket Client` 换成你的节点标签）。**Editor** 标记工作流编辑器在 Previous Nodes 中提示的路径（输出契约）；**Worker** 标记 worker 实际通过 `out` 返回的路径，依据“端口”一节所示的输出。

- `$("WebSocket Client").item.json.result` (string) = `"{\"type\":\"ack\",\"id\":\"msg_881\"}"`: 确认或响应


## 工作原理

建立 WebSocket 连接并发送一条消息，然后立即关闭，或等待返回的第一条消息。

1. 解析配置。`connection_id`、`message` 和 `waitForResponse`（默认 false）缺失时回退到输入 payload 中的同名键；`connection_id` 和 `message` 为必填。
2. 解析凭据：URL 为 `config.url`；若密钥含 `token`，握手时发送 `Authorization: Bearer <token>`。
3. 建立连接，连接打开后立即发送 `message`。
4. 未启用 `waitForResponse` 时，关闭连接并返回 `{ result: "sent" }`；启用时，等待第一条传入消息，关闭连接并以文本形式在 `result` 中返回。

## 在工作流中

### 节点

```json
{
  "node_id": "node-push-event",
  "label": "Push event",
  "operator_slug": "io.websocket",
  "operator_version": "1.0.0",
  "config": {
    "connection_id": "pi-credential-xxxx",
    "message": "{{ JSON.stringify($json.event) }}",
    "waitForResponse": true
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "result": "{\"type\":\"ack\",\"id\":\"msg_881\"}"
  },
  "port": "out"
}
```

## 输出端口 (代码中的行为)

### `out`

消息已发送（`result` 为 `"sent"`），或在启用 `waitForResponse` 时收到了第一条回复（`result` 为其文本）。

```json
{
  "result": "{\"type\":\"ack\",\"id\":\"msg_881\"}"
}
```

### `error`

缺少必填字段、无法解析凭据，或连接失败。

```json
{
  "error": "Unexpected server response: 401"
}
```

## 代码中的行为

- `connection_id`: URL 取自凭据配置的 `url`；密钥中只读取 `token`。`api-key` 和 `basic-auth` 类型的密钥不会在握手中添加请求头。以 `ws://` 或 `wss://` 开头的值会直接用作 URL，不带认证。
- `message`: 必须为字符串。如需发送 JSON，请先构造字符串，例如 `{{ JSON.stringify($json.event) }}`。
- `waitForResponse`: 等待没有时间限制。若服务器始终不发送消息，或未发送就关闭连接，节点将无法结束。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `Unexpected server response: <status>` | `error` | 服务器拒绝了协议升级（例如 401 或 404）。请检查 URL 和凭据中的 token。 |
| `message is required` | `error` | 配置和输入 payload 中的消息均为空（凭据缺失时对应 `connection_id is required`）。 |
| `Failed to resolve connection <connection_id>: <detail>` | `error` | 凭据不存在或此工作流无权使用。 |

## 说明与限制

- 只返回第一条传入消息，后续消息会被丢弃。二进制回复会被转换为文本。
- 每次运行都会新建并关闭连接。不会重试。


## 契约（JSON Schema）

### All (`*.definition.js`)

```json
{
  "slug": "io.websocket",
  "name": "WebSocket Client",
  "category": "io",
  "version": "1.0.0",
  "description": "Send message to WebSocket Server.",
  "capabilities": [
    "websocket",
    "realtime",
    "messaging"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "connection_id": {
        "type": "string",
        "title": "WebSocket Credential",
        "description": "Credential for the WebSocket endpoint. Accepts credentials of type `api-key`, `basic-auth`, or `object` (custom handshake headers).",
        "ui_widget": "connection_picker",
        "ui_options": {
          "credential_types": [
            "api-key",
            "basic-auth",
            "object"
          ],
          "types": [
            "websocket"
          ]
        }
      },
      "message": {
        "type": "string",
        "description": "Message to send"
      },
      "waitForResponse": {
        "type": "boolean",
        "default": false
      }
    },
    "required": [
      "connection_id",
      "message"
    ]
  },
  "input_contract_schema": {
    "type": "object",
    "properties": {
      "connection_id": {
        "type": "string"
      },
      "message": {
        "type": "string"
      },
      "waitForResponse": {
        "type": "boolean"
      }
    },
    "required": [
      "connection_id",
      "message"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "result": {
        "type": "string",
        "description": "Ack or Response"
      }
    }
  },
  "ports": [
    {
      "port_id": "out",
      "label": "Sent/Response",
      "description": "Message sent or response received",
      "is_default": true,
      "supports_condition": true
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Connection or transmission error",
      "is_default": false,
      "supports_condition": false
    }
  ],
  "execution_mode": "async",
  "required_resources": [],
  "compatible_worker_pools": [
    "standard-io",
    "realtime"
  ],
  "tags": [
    "realtime",
    "messaging"
  ],
  "is_stateful": false,
  "publisher": {
    "identity": "org_link_loom",
    "profile": {
      "name": "Link Loom",
      "verified": true,
      "url": "https://me.veripass.com/link-loom",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "properties": {
    "connection_id": {
      "type": "string",
      "title": "WebSocket Credential",
      "description": "Credential for the WebSocket endpoint. Accepts credentials of type `api-key`, `basic-auth`, or `object` (custom handshake headers).",
      "ui_widget": "connection_picker",
      "ui_options": {
        "credential_types": [
          "api-key",
          "basic-auth",
          "object"
        ],
        "types": [
          "websocket"
        ]
      }
    },
    "message": {
      "type": "string",
      "description": "Message to send"
    },
    "waitForResponse": {
      "type": "boolean",
      "default": false
    }
  },
  "required": [
    "connection_id",
    "message"
  ]
}
```

### input_contract_schema

```json
{
  "type": "object",
  "properties": {
    "connection_id": {
      "type": "string"
    },
    "message": {
      "type": "string"
    },
    "waitForResponse": {
      "type": "boolean"
    }
  },
  "required": [
    "connection_id",
    "message"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "result": {
      "type": "string",
      "description": "Ack or Response"
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "out",
    "label": "Sent/Response",
    "description": "Message sent or response received",
    "is_default": true,
    "supports_condition": true
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Connection or transmission error",
    "is_default": false,
    "supports_condition": false
  }
]
```
