Created
February 25, 2016 13:27
-
-
Save selenologist/b13a28d6881b5817d4ba to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "enet" | |
network = { | |
status = "[unloaded]", | |
last_msg = "[no msg]" | |
} | |
function server_init(self) | |
self.status = "[server]" | |
self.received = 0 | |
self.sent = 0 | |
self.host = enet.host_create("localhost:31337") | |
end | |
function server_run(self) | |
local event = self.host:service(0) -- 0ms timeout | |
if event and event.type == "receive" then | |
self.received = self.received + 1 | |
self.last_msg = event.data .. " from " .. tostring(event.peer) | |
end | |
self.status = | |
string.format("[%s] %i↑ %i↓", | |
os.date("%x", os.time()), | |
self.sent, | |
self.received) | |
end | |
function client_init(self) | |
self.status = "[client]" | |
self.host = enet.host_create() | |
self.server = self.host:connect("localhost:31337") | |
self.timeouts = 0 | |
end | |
function client_run(self) | |
local event = self.host:service(0) | |
if event then | |
if event.type == "connect" then | |
self.status = "Connected to " .. tostring(event.peer) | |
event.peer:send("Hi there") | |
elseif event.type == "receive" then | |
if event.data == "QUIT" then | |
self.server:disconnect() | |
self.host:flush() | |
self.status = "[disconnected]" | |
self.run = function() end | |
print("Client thread exiting") | |
end | |
self.last_msg = event.data | |
event.peer:send("reply " .. event.data) | |
end | |
end | |
self.timeouts = self.timeouts + 1 | |
if self.timeouts % 5 == 0 then | |
self.server:send("timeout " .. self.timeouts) | |
end | |
end | |
function love.draw() | |
love.graphics.print(network.status, 0, 0) | |
love.graphics.print(network.last_msg, 0, 20) | |
end | |
function love.update() | |
network:run() | |
end | |
function love.load(arg) | |
if arg[2] == "server" then | |
print("Starting server") | |
network.init = server_init | |
network.run = server_run | |
else | |
print("Starting client") | |
network.init = client_init | |
network.run = client_run | |
end | |
network:init() | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment