Hey guys. I'm attempting to make 2 scripts talk to each other via websocket in godot4, but I'm not sure how to do that- example projects seem to be using depreciated classes like WebsocketServer and WebsocketClient. I attempted to make something following the documentation but can't quite get it to work.
Client code is straight copied from documentation:
extends Node
var socket = WebSocketPeer.new()
func _ready():
socket.connect_to_url("wss://localhost:8099")
func _process(_delta):
socket.poll()
#print(socket.get_connected_host())
var state = socket.get_ready_state()
if state == WebSocketPeer.STATE_OPEN:
while socket.get_available_packet_count():
print("Packet: ", socket.get_packet())
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.
Server code is based on TCPServer(since it's actually capable of listening) using WebsocketPeer as remote peer as suggested by documentation(documentation also recommends looking up online tutorial but I don't think that one is out yet):
extends Node
var server= TCPServer.new()
var connector
var sender= WebSocketPeer.new()
func _ready():
server= TCPServer.new()
print(server.listen(8099))
print(server.get_local_port())
print(server.is_connection_available())
func _process(_delta):
var conn= server.is_connection_available()
if conn:
if !connector:
connector= server.take_connection()
connector.set_no_delay(true)
sender.accept_stream(connector)#this supposedly performs the handshake according to documentation?
print(connector.get_status())
while sender.get_ready_state()!= WebSocketPeer.STATE_OPEN:
sender.poll()
# Once the connection is opensend a packet
sender.put_packet([1,2,"aaa"])
Print outputs in order are:
0
8099
false
2
So that part works fine.
The problem is sender.get_ready_state() of the client never changes from 0(CONNECTING) to 1(OPEN) and I can't send packets.
I'd be grateful for any tips/examples of how this actually should work