Page 1 of 1

Has anyone got a simple enet example? [solved]

Posted: Fri Apr 23, 2021 6:03 am
by togFox
I looked at the wiki page and that example works but I find it difficult to translate that example into a useful app. It is demonstrating an endless loop and doesn't seem to use host/peers in a way I'd expect. For example, the server.lua example creates a 'server' with this line but then fails to actually use that server.

Code: Select all

local server = host:connect("localhost:6789")
I can't track what's going on here. The example also shows the client sending a message, but only in response to a 'connect' message or a 'pong' message from the server. This example implies that the client can only respond to the server and not send a message in isolation. I must be understanding this wrong.

I tried to break this down and user servers and peers using a more practical love.update loop. It creates a 'server' and a 'client' on the same machine - in the same script. IN other words, this one script will send a message from one port to another.

Code: Select all

enet = require "enet"

-- scoping things 'global' for debugging purposes	
enethost = nil
hostevent = nil
clientpeer = nil

function love.load(args)

	-- establish host for receiving msg
	enethost = enet.host_create("localhost:6750")
	
	-- establish a connection to host on same PC
	enetclient = enet.host_create()
	clientpeer = enetclient:connect("localhost:6750")	--! hard coded for debugging

	end

function love.update(dt)
	ServerListen()	
	ClientSend()
end

function love.draw()
end

function ServerListen()

	hostevent = enethost:service(100)
	
	if hostevent then
		print("Server detected message type: " .. hostevent.type)
		if hostevent.type == "connect" then 
			print(hostevent.peer, "connected.")
		end
		if hostevent.type == "receive" then
			print("Received message: ", hostevent.data, hostevent.peer)
		end
	end
end

function ClientSend()
	clientpeer:send("Hi")
end

It doesn't work. When I query the clientpeer.status it says "connecting" forever and ever. The Server is not accepting the connection. I'd like to make this work and then include it on the wiki if the community feels that is useful.

Re: Has anyone got a simple enet example? [solved]

Posted: Fri Apr 23, 2021 10:10 am
by togFox
I was missing a line. This function is now complete and working:

Code: Select all

function ClientSend()
	enetclient:service(100)
	clientpeer:send("Hi")
end