Help with connecting Godot web socket client to Node.js web socket server

Godot Version

Godot 4.2.1

Question

I’m trying to make a basic connection between Godot and a Node.js backend, but I end up with code -1 errors
Client (on Godot):

extends Node

var socket = WebSocketPeer.new()
const URL = 'wss://locahost:8080/'

func _ready():
	socket.connect_to_url(URL)

func _process(delta):
	socket.poll()
	var state = socket.get_ready_state()
	if state == WebSocketPeer.STATE_OPEN:
		print('we connected')
	elif state == WebSocketPeer.STATE_CLOSING:
		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])

this script is attached to a Node that is the root of a scene, that’s all the setup done

The node.js side if relevant:

const { createServer } = require('http');
const { WebSocketServer } = require('ws');

const server = createServer();
const wss = new WebSocketServer({ server });

wss.on('connection', function connection(ws) {
    ws.on('error', console.error);      
    console.log('someone connected');
});

server.listen(8080, () => {
    console.log("Listening on port 8080");
}); 

I’m using the ws library to create this node.js web socket server, I have tried connecting to this server via browser and via a node.js client using the same library, and they work fine.

Change URL line to.

const URL = 'ws://127.0.0.1:8080/'

My guess there are two things going on. By starting with wss, Godot assumes you want to open the connection with a TLS cert. The other being localhost not resolving to 127.0.0.1 properly (Not really sure, the exact technical reason, be have defiantly ran into this is the past with other tech).

1 Like

@ahmed349 I am struggling with the same issue. did you ever end up getting yours to work?

It’s been a while since that project, but basically there was nothing wrong the code, a mixture of restarting Godot and my computer, disabling unused network adapters, and potentially creating a different project with the same code fixed it, it was probably something bugging out with godot, because i had tried rewriting the server in other frameworks/backends and they worked with any client but godot’s, so if you are 100% sure about your backend and your godot setup just try the basic troubleshooting i mentioned, and also check the other comment about wss

1 Like