Godot 4 equivalent of WebSocketClients' get_peer()

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

Im converting a Godot 3 game to Godot 4. The game has a Server script (c#) which uses a WebServerClient to communicate with a WebSocketServer.

WebSocketClient doesn’t exist anymore in Godot 4, we now have WebSocketPeer. What I need is the Godot 4’s equivalent of the following code:

WebSocketClient network = new WebSocketClient();
UTF8Encoding utf8 = new UTF8Encoding();

private void _DataReceived() {
:bust_in_silhouette: Reply From: jgodfrey

While I haven’t verified anything, a few observations:

  • In the 3.5 code posted above, network.GetPeer(1) returns a WebSocketPeer
  • In the 4.0 code, you’re already working with a WebSocketPeer object

So, from that point forward, things should be, at least, similar…

Further, in the 3.5 code, you make a GetPacket call on the WebSocketPeer object. Looking, the 4.0 version of WebSocketPeer also has a GetPacket method.

So, it seems like the above should just require a comparison of the related docs and some minimal refactoring to get workigng in Godot 4.

Turns out it was something along those lines, thanks for the help!

jgee_23_ | 2023-03-09 09:48

:bust_in_silhouette: Reply From: jgee_23_

Theres been some changes to how Gd4’s new WebSocketPeer works compared to Gd3’s WebSocketClient. Here’s my Gd3 implementation:

public override void _Ready() {
public override void _Process(float delta) {
private void _DataReceived() {

private void setup_connections() {
	network.Connect("connection_established", this, "connection_succeeded");
	network.Connect("connection_closed", this, "server_disconnected");
	network.Connect("connection_error", this, "connection_failed");
	network.Connect("server_close_request", this, "forced_disconnect");
	network.Connect("data_received", this, "_DataReceived");

public void connect_to_server() {
	Error err = network.ConnectToUrl(url);
	if (err != Error.Ok) {
		GD.Print("Unable to Connect");

To summarize it, I connect the WebSocketClient’s “data_received” signal to the _DataReceived function to handle packets received there. However, this signal (as far as I can tell) was removed in Gd4. In order to tackle this problem, I just followed the steps in the WebSocketPeer documentation which for some reason I missed even though I visited the page a bunch of times! Here’s the result:

public override void _Process(double delta) {
	WebSocketPeer.State state = network.GetReadyState();
	if (state == WebSocketPeer.State.Open) {
		while (network.GetAvailablePacketCount() > 0) {
	} else if (state == WebSocketPeer.State.Closed) {
		int code = network.GetCloseCode();
		string reason = network.GetCloseReason();
		GD.Print("Disconnected from server:   code:", code, "   reason:", reason);