Skip to content

Commit fa8cd06

Browse files
Update WebSocket documentation for Godot 4
1 parent 3c2412d commit fa8cd06

File tree

1 file changed

+104
-103
lines changed

1 file changed

+104
-103
lines changed

tutorials/networking/websocket.rst

Lines changed: 104 additions & 103 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
:article_outdated: True
1+
:article_outdated: False
22

33
.. _doc_websocket:
44

@@ -36,61 +36,50 @@ This example will show you how to create a WebSocket connection to a remote serv
3636

3737
::
3838

39-
extends Node
39+
extends Node
4040

4141
# The URL we will connect to
42-
export var websocket_url = "wss://libwebsockets.org"
43-
44-
# Our WebSocketClient instance
45-
var _client = WebSocketClient.new()
46-
47-
func _ready():
48-
# Connect base signals to get notified of connection open, close, and errors.
49-
_client.connection_closed.connect(_closed)
50-
_client.connection_error.connect(_closed)
51-
_client.connection_established.connect(_connected)
52-
# This signal is emitted when not using the Multiplayer API every time
53-
# a full packet is received.
54-
# Alternatively, you could check get_peer(1).get_available_packets() in a loop.
55-
_client.data_received.connect(_on_data)
56-
57-
# Initiate connection to the given URL.
58-
var err = _client.connect_to_url(websocket_url, ["lws-mirror-protocol"])
59-
if err != OK:
60-
print("Unable to connect")
61-
set_process(false)
62-
63-
func _closed(was_clean = false):
64-
# was_clean will tell you if the disconnection was correctly notified
65-
# by the remote peer before closing the socket.
66-
print("Closed, clean: ", was_clean)
67-
set_process(false)
68-
69-
func _connected(proto = ""):
70-
# This is called on connection, "proto" will be the selected WebSocket
71-
# sub-protocol (which is optional)
72-
print("Connected with protocol: ", proto)
73-
# You MUST always use get_peer(1).put_packet to send data to server,
74-
# and not put_packet directly when not using the MultiplayerAPI.
75-
_client.get_peer(1).put_packet("Test packet".to_utf8())
76-
77-
func _on_data():
78-
# Print the received packet, you MUST always use get_peer(1).get_packet
79-
# to receive data from server, and not get_packet directly when not
80-
# using the MultiplayerAPI.
81-
print("Got data from server: ", _client.get_peer(1).get_packet().get_string_from_utf8())
82-
83-
func _process(delta):
84-
# Call this in _process or _physics_process. Data transfer, and signals
85-
# emission will only happen when calling this function.
86-
_client.poll()
87-
88-
This will print:
42+
@export var websocket_url = "wss://ws.postman-echo.com/raw"
43+
44+
var socket = WebSocketPeer.new()
45+
46+
47+
func _ready():
48+
socket.connect_to_url(websocket_url)
49+
50+
# Send a message every 5 seconds
51+
var timer = Timer.new()
52+
timer.wait_time = 5.0
53+
timer.timeout.connect(_send_message)
54+
add_child(timer)
55+
timer.start()
56+
57+
58+
func _send_message():
59+
socket.send_text("Hello websockets!")
60+
61+
62+
func _process(delta):
63+
socket.poll()
64+
var state = socket.get_ready_state()
65+
if state == WebSocketPeer.STATE_OPEN:
66+
while socket.get_available_packet_count():
67+
print("Packet: ", socket.get_packet().get_string_from_utf8())
68+
elif state == WebSocketPeer.STATE_CLOSING:
69+
# Keep polling to achieve proper close.
70+
pass
71+
elif state == WebSocketPeer.STATE_CLOSED:
72+
var code = socket.get_close_code()
73+
var reason = socket.get_close_reason()
74+
print("WebSocket closed with code: %d, reason %s. Clean: %s" % [code, reason, code != -1])
75+
set_process(false) # Stop processing.
76+
77+
78+
This will send a message every 5 seconds that will be echoed back
8979

9080
::
9181

92-
Connected with protocol:
93-
Got data from server: Test packet
82+
Packet: Hello websockets!
9483

9584
Minimal server example
9685
^^^^^^^^^^^^^^^^^^^^^^
@@ -99,63 +88,75 @@ This example will show you how to create a WebSocket server that listens for rem
9988

10089
::
10190

102-
extends Node
103-
104-
# The port we will listen to
105-
const PORT = 9080
106-
# Our WebSocketServer instance
107-
var _server = WebSocketServer.new()
108-
109-
func _ready():
110-
# Connect base signals to get notified of new client connections,
111-
# disconnections, and disconnect requests.
112-
_server.client_connected.connect(_connected)
113-
_server.client_disconnected.connect(_disconnected)
114-
_server.client_close_request.connect(_close_request)
115-
# This signal is emitted when not using the Multiplayer API every time a
116-
# full packet is received.
117-
# Alternatively, you could check get_peer(PEER_ID).get_available_packets()
118-
# in a loop for each connected peer.
119-
_server.data_received.connect(_on_data)
120-
# Start listening on the given port.
121-
var err = _server.listen(PORT)
122-
if err != OK:
123-
print("Unable to start server")
124-
set_process(false)
125-
126-
func _connected(id, proto):
127-
# This is called when a new peer connects, "id" will be the assigned peer id,
128-
# "proto" will be the selected WebSocket sub-protocol (which is optional)
129-
print("Client %d connected with protocol: %s" % [id, proto])
130-
131-
func _close_request(id, code, reason):
132-
# This is called when a client notifies that it wishes to close the connection,
133-
# providing a reason string and close code.
134-
print("Client %d disconnecting with code: %d, reason: %s" % [id, code, reason])
135-
136-
func _disconnected(id, was_clean = false):
137-
# This is called when a client disconnects, "id" will be the one of the
138-
# disconnecting client, "was_clean" will tell you if the disconnection
139-
# was correctly notified by the remote peer before closing the socket.
140-
print("Client %d disconnected, clean: %s" % [id, str(was_clean)])
141-
142-
func _on_data(id):
143-
# Print the received packet, you MUST always use get_peer(id).get_packet to receive data,
144-
# and not get_packet directly when not using the MultiplayerAPI.
145-
var pkt = _server.get_peer(id).get_packet()
146-
print("Got data from client %d: %s ... echoing" % [id, pkt.get_string_from_utf8()])
147-
_server.get_peer(id).put_packet(pkt)
148-
149-
func _process(delta):
150-
# Call this in _process or _physics_process.
151-
# Data transfer, and signals emission will only happen when calling this function.
152-
_server.poll()
91+
extends Node
92+
93+
# The port we will listen to
94+
const PORT = 9080
95+
96+
# Our WebSocketServer instance
97+
var _server = WebSocketMultiplayerPeer.new()
98+
99+
# Keeps track of the connected peer IDs
100+
var peer_ids: Array[int] = []
101+
102+
103+
func _ready():
104+
# Connect base signals to get notified of new client connections,
105+
# and disconnections.
106+
_server.peer_connected.connect(_connected)
107+
_server.peer_disconnected.connect(_disconnected)
108+
109+
# Start listening on the given port.
110+
var err = _server.create_server(PORT)
111+
if err != OK:
112+
print("Unable to start server")
113+
set_process(false)
114+
115+
116+
func _connected(id):
117+
peer_ids.append(id)
118+
119+
# This is called when a new peer connects, "id" will be the assigned peer id,
120+
print("Peer %d connected" % id)
121+
122+
123+
func _disconnected(id):
124+
peer_ids.erase(id)
125+
126+
# This is called when a client disconnects, "id" will be the one of the
127+
# disconnecting client
128+
var peer = _server.get_peer(id)
129+
var code = peer.get_close_code()
130+
var reason = peer.get_close_reason()
131+
print("Peer %s closed with code: %d, reason %s. Clean: %s" % [id, code, reason, code != -1])
132+
133+
134+
func _process(delta):
135+
# Call this in _process or _physics_process.
136+
# Data transfer, and signals emission will only happen when calling this function.
137+
_server.poll()
138+
139+
for peer_id in peer_ids:
140+
var peer = _server.get_peer(peer_id)
141+
peer.poll()
142+
143+
var peer_state = peer.get_ready_state()
144+
if peer_state == WebSocketPeer.STATE_OPEN:
145+
while peer.get_available_packet_count():
146+
var packet_text = peer.get_packet().get_string_from_utf8()
147+
print(" Got data from peer %s: %s" % [peer_id, packet_text])
148+
149+
# Echo the packet back
150+
peer.send_text(packet_text)
151+
elif peer_state == WebSocketPeer.STATE_CLOSING:
152+
# Keep polling to achieve proper close.
153+
pass
153154

154155
This will print (when a client connects) something similar to this:
155156

156157
::
157158

158-
Client 1348090059 connected with protocol: selected-protocol
159+
Client 1348090059 connected
159160
Got data from client 1348090059: Test packet ... echoing
160161

161162
Advanced chat demo

0 commit comments

Comments
 (0)