How to set up a Python WebSocket Server with Godot 4’s WebSocketPeer Client. [Tutorial]

RMAG news

Since Godot 4 WebSocketServer and WebSocketClient have been disappeared from the API.
I tried to explain it to myself how Godot 4’s new API works since the docs have not been updated using the downloadable example project you can find here: https://godotengine.org/asset-library/asset/2800
However, it seems that only one WebSocketPeer can connect to each other, consequentially, when the server connected to one peers, its over, other peers dont get the chance to connect, too!
Now, I found a pretty solution using python’s websockets module.
1) Set up a client with Godot 4’s WebSocketPeer

Use the example project (link mentioned above) to set up the client; or use this script on Node:

extends Node

# The URL we will connect to.
var websocket_url = “ws://localhost:12345” # Replace with actual server address and port
var socket := WebSocketPeer.new()

func _ready():
if socket.connect_to_url(websocket_url) != OK:
print(“Could not connect.”)
set_process(false)

func _process(_delta):
socket.poll()

if socket.get_ready_state() == WebSocketPeer.STATE_OPEN:
while socket.get_available_packet_count():
print(“Recv. >”,socket.get_packet().get_string_from_ascii(),”<“)

func _exit_tree():
socket.close()

func _input(event):
# Send “Ping!” to the server when Enter is pressed.
if event is InputEventKey and event.pressed and event.keycode == KEY_ENTER:
if socket.get_ready_state() != WebSocketPeer.STATE_OPEN:
print(“You are currently not connected to the server.”)
else:
socket.send_text(“Ping!”)

2) Set up a python server using websockets module

Follow the short tutorial on https://pythonexamples.org/python-websockets-example/ how to set up a websocket server. I have not done anything else but copy-pasting the example code and it worked. Use this for example:

import asyncio
import websockets

# Define a callback function to handle incoming WebSocket messages
async def handle_websocket(websocket, path):
try:
while True:
message = await websocket.recv()
print(f”Received message: >{message}<“)

# XXX: Do some stuff here with the message.

response = “Pong!”
await websocket.send(response)
except websockets.ConnectionClosed:
pass

if __name__ == “__main__”:
# Start the WebSocket server
start_server = websockets.serve(handle_websocket, “localhost”, 12345)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()