You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何正确配置Godot WebSocketClient与Python服务端连接?

问题原因与解决方法

核心问题是协议不匹配:你的Python服务端是普通TCP Socket,而Godot客户端使用的是WebSocket协议。WebSocket是基于TCP的应用层协议,需要完成特定的握手流程,裸TCP服务端无法处理WebSocket的连接请求,导致连接失败,触发Condition "!is_connected_to_host()" is true错误。

方案1:改用WebSocket服务端(推荐,匹配Godot客户端)

使用Python的websockets库实现WebSocket服务端,示例代码:

import asyncio
import websockets

async def handle_connection(websocket):
    print("Connection Established!")
    try:
        while True:
            data = await websocket.recv()
            print("Sender Says :", data)
            await websocket.send("General Kenobi!")
    except websockets.exceptions.ConnectionClosed:
        print("Connection Terminated!")

async def main():
    async with websockets.serve(handle_connection, "127.0.0.1", 6000):
        print("Waiting for connection...")
        await asyncio.Future()  # 保持服务运行

asyncio.run(main())

使用前需要安装依赖:

pip install websockets

方案2:将Godot客户端改为TCP客户端(适配现有Python服务端)

如果要保留原TCP服务端,修改Godot代码使用StreamPeerTCP替代WebSocketClient:

tool
extends Node2D

var _client = StreamPeerTCP.new()
var err

func _init():
    err = _client.connect_to_host("127.0.0.1", 6000)
    print("err=", err)
    if err != OK:
        print("Unable to connect")
        set_process(false)

func _process(delta):
    match _client.get_status():
        StreamPeerTCP.STATUS_CONNECTED:
            # 连接成功后发送初始消息
            if _client.get_available_packet_count() == 0 and not _client.is_write_blocked():
                _client.put_packet("Hello there".to_utf8())
            # 接收服务器数据
            while _client.get_available_packet_count() > 0:
                print("Got data from server: ", _client.get_packet().get_string_from_utf8())
            _client.poll()
        StreamPeerTCP.STATUS_ERROR:
            print("Connection error")
            set_process(false)
        StreamPeerTCP.STATUS_DISCONNECTED:
            print("Closed connection")
            set_process(false)

原错误补充说明

原Godot代码中,_connected回调尝试调用get_peer(1).put_packet,但由于WebSocket握手未完成(服务端不支持WebSocket),客户端实际未建立有效连接,因此触发了该错误提示。

内容的提问来源于stack exchange,提问作者cak3_lover

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 06:30:50