Multiplayer in HTML5 Game

Godot Version

4.7

Question

I need help converting my ENet multiplayer game so it works in the browser. I understand that I need to use WebRTC or WebSocket, but I’m not sure how to do it. I could easily change it from ENet to work with WebSocket, but it still doesn’t work in the browser. I have tried both local hosting my game and running it on itch.io. I have also tried running the game with the player hosting the game on the desktop app version, and clients using the browser. If I host on the desktop app and a client joins on the desktop app, everything works fine. I would prefer it if the solution let me keep all the rpc’s in my project the same.

If I host the game on the desktop app and join the game in the browser (using localhost) on the same device I get this error: WebSocket connection to ‘ws://127.0.0.1:6000/’ failed:

I am not sure what I need to add/do to make it work in the browser.

Below is a snippet of my code that shows some of the multiplayer functionality in my game currently.

var peer = WebSocketMultiplayerPeer.new()

func _ready() -> void:
	Global.in_game = true
	$Transition/AnimationPlayer.play("transition2")
	if Global.hosting:
		peer.create_server(Global.port)
		multiplayer.multiplayer_peer = peer
		multiplayer.peer_connected.connect(add_player)
		multiplayer.peer_disconnected.connect(delete_player)
		add_player()
		if Global.online:
			upnp_setup()
	else:
		peer.create_client("ws://"+Global.ip_address+":"+str(Global.port))
		multiplayer.multiplayer_peer = peer

Ain’t read ANY of this, but I like the idea. Keep me updated, okay? :wink:

The error code that comes after that is important; but you probably don’t want websockets.

Websockets will promote to Secure websockets if hosted on a Secure (HTTPS) site. You will need a registered certificate to host a game with these websockets. I’ve done so because I have a central server with a domain name and certificate from LetsEncrypt. Players hosting their own listen server will be unable to. You can to some degree work around this by specifying TLSOptions.client_unsafe() as the create_client second option, but I’m pretty sure it will still fail without a Certificate on normal hosts such as itch.io. Websockets are also built upon TCP which will be slower than other standards.

WebRTC will be a better route by not having those issues, allowing UDP and as I understand it, random insecure servers.