Godot 4 WebSocket example

Godot Version

4.2

Question

Hi, how can I make a WebSocket connection, the document is not up to date
WebSocket — Godot Engine (stable) documentation in English

1 Like

Hello,
I’m also currently trying to implement websocket communication.
This is what I’ve done so far.

var socket: WebSocketPeer = WebSocketPeer.new()

func _process(delta):
	socket.poll()
	var state = socket.get_ready_state()
	if state == WebSocketPeer.STATE_OPEN:
		while socket.get_available_packet_count():
			var payload_string = socket.get_packet().get_string_from_utf8()
			print("Packet: ", payload_string)
			$MainContainer/Label.text += payload_string + "\n"
	elif state == WebSocketPeer.STATE_CLOSING:
		# Keep polling to achieve proper close.
		pass
	elif state == WebSocketPeer.STATE_CLOSED:
		var code = socket.get_close_code()
		var reason = socket.get_close_reason()
		print("WebSocket closed with code: %d, reason %s. Clean: %s" % [code, reason, code != -1])
		set_process(false) # Stop processing.