How do I get Websocket put_packet() to work?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By clym

Hi there,
I have a basic script to connect to a web-socket. I successfully connect to the socket & get_packet() function works - however put_packet() is returning 0 every time and the server doesn’t seem to be picking it up. Any ideas why get_packet is working, but put_packet isn’t? Thanks for checking this out! Appreciate any thoughts.

below is the code:

extends Node

export var websocket_url = "ws://localhost:8080"
var _client = WebSocketClient.new()

func _ready():
_client.connect("connection_closed", self, "_closed")
_client.connect("connection_error", self, "_closed")
_client.connect("connection_established", self, "_connected")
_client.connect("data_received", self, "_on_data")

var err = _client.connect_to_url(websocket_url)
if err != OK:
	print("Unable to connect")
	$Label.text = "Unable to connect"
	set_process(false)

func _closed(was_clean = false):
print("Closed, clean: ", was_clean)
$Label.text = "Closed, clean: " + was_clean
set_process(false)

func _connected(proto = ""):
print("Connected with protocol: ", proto)
$Label.text = "Connected with protocol: " + proto
_client.get_peer(1).put_packet("Test packet".to_utf8())

func _on_data():
var a = _client.get_peer(1).get_packet().get_string_from_utf8()
print("Got data from server: ", _client.get_peer(1).get_packet().get_string_from_utf8())

func _process(delta):
_client.poll()
:bust_in_silhouette: Reply From: clym

So I found the answer: I asked a friend and he said the put_packet() function send’s BINARY to the server side. I had to program that on the server side to convert the Binary to UTF-8.

:bust_in_silhouette: Reply From: burdock

You need to set the peer’s write mode to Text.

You can do this with:

_client.get_peer(1).set_write_mode(WebSocketPeer.WRITE_MODE_TEXT)

Great, this solved my problem!

Array | 2022-12-20 09:35