Of course! Here is the same minimal working example, but this time using Python for the server instead of Node.js.
The beauty of using a standard protocol like WebSockets is that the Godot client code remains exactly the same. We are just swapping out the backend implementation.
Prerequisites
Python: Install from python.org (v3.7+ recommended for asyncio).
websockets library: A popular and easy-to-use library for building WebSocket servers in Python.
Godot 4.4: Same as before.
Step 1: Python Server
Install Dependencies
Open your terminal or command prompt and install the websockets library:
bash
pip install websockets
server.py
Create a file named server.py with this code. It uses Python's asyncio library to handle connections concurrently.
python
import asyncio
import websockets
import json
async def handler(websocket, path):
"""
This function is called for each new client that connects.
"""
print("Client connected!")
# Send a sample question to the new client
question = {
"type": "question",
"text": "What is the capital of France?",
"options": ["Paris", "London", "Berlin", "Madrid"]
}
await websocket.send(json.dumps(question))
try:
# Listen for incoming messages (e.g., answers)
async for message in websocket:
data = json.loads(message)
print(f"Received answer from client: {data['answer']}")
# Check the answer and prepare a response
is_correct = data['answer'] == 'Paris'
response = {
"type": "result",
"correct": is_correct
}
await websocket.send(json.dumps(response))
except websockets.exceptions.ConnectionClosed:
print("Client disconnected.")
finally:
# This block runs when the client disconnects
print("Connection handler finished.")
async def main():
# Use "0.0.0.0" to listen on all available network interfaces
# This makes it accessible from other devices on your local network
async with websockets.serve(handler, "0.0.0.0", 8080):
print("WebSocket server running on ws://<your-ip>:8080")
await asyncio.Future() # Run forever
if __name__ == "__main__":
asyncio.run(main())
Run the Server
bash
python server.py
It listens on port 8080. To find your machine's local IP, use ipconfig on Windows or ifconfig on macOS/Linux. You will need this IP for the Godot client if you're testing on a different device.
Step 2: Godot 4.4 Client (No Changes Needed)
The Godot client code is identical to the one used for the Node.js server. The client only cares about the WebSocket protocol and the JSON message format, not the language the server is written in.
For completeness, here is the QuizClient.gd script again.
QuizClient.gd
gdscript
extends Node
var websocket = WebSocketPeer.new()
var connected = false
# UI elements (drag these from the scene tree in Godot editor)
@onready var question_label = $QuestionLabel
@onready var options_container = $OptionsContainer
@onready var result_label = $ResultLabel
func _ready():
# IMPORTANT: Connect to your Python server's IP address.
# Use "localhost" if running Godot on the same machine.
# Use your server's local IP (e.g., "192.168.1.100") if on a different device.
var server_url = "ws://localhost:8080"
var err = websocket.connect_to_url(server_url)
if err != OK:
print("Connection failed: ", err)
else:
print("Connecting to server at ", server_url)
func _process(delta):
websocket.poll()
var state = websocket.get_ready_state()
if state == WebSocketPeer.STATE_OPEN:
if not connected:
connected = true
print("Connected!")
while websocket.get_available_packet_count():
var packet = websocket.get_packet()
if packet:
var data = packet.get_string_from_utf8()
handle_message(JSON.parse(data).result)
elif state == WebSocketPeer.STATE_CLOSED:
print("Connection closed")
connected = false
func handle_message(data):
if data.type == "question":
question_label.text = data.text
# Clear and add option buttons
for child in options_container.get_children():
child.queue_free()
for option in data.options:
var btn = Button.new()
btn.text = option
btn.connect("pressed", Callable(self, "_on_answer_selected").bind(option))
options_container.add_child(btn)
elif data.type == "result":
result_label.text = "Correct? " + ("Yes!" if data.correct else "No")
func _on_answer_selected(answer):
# Send answer back to server
var message = {
"answer": answer
}
websocket.send_text(JSON.stringify(message))
Run the Client
Set up your scene in Godot as described in the previous example.
Update the server_url in the _ready() function to match your Python server's IP if necessary.
Run the scene (F6).
How It Works
The flow is exactly the same as with the Node.js server:
Server Starts: The Python asyncio event loop starts the websockets server.
Client Connects: The handler function is created for the new connection.
Receive Question: The server sends the question JSON, which the Godot client parses and displays.
Send Answer: The client sends its answer back to the server.
Receive Result: The Python server's async for loop processes the answer, checks it, and sends the result back.
This demonstrates the power of using standardized protocols. You can choose the best tool for the job (e.g., Python for its data science and simplicity, Node.js for its massive async I/O ecosystem) without forcing changes on the client-side application.