Creating a server using ENet
Posted: Tue Jun 07, 2016 5:36 am
Hello there! Thank you for visiting my help thread.
I'm trying to create a game with multiplayer in it, but the problem is I don't have any knowledge with networking. I'm trying to create a server with ENet using external IP and random allocated port (maybe). Without any further chit-chat, let's jump to the code. I'm going to post the server only. First one is the main.lua and the second one is the thread.lua.
The problem is, when I run the code, the message always printed "Server state: unavailable" no matter how long I waited. I'm requesting a help from you. If you know anything about networking, please do me a favor! Thank you for you time that you're still reading this!
I'm trying to create a game with multiplayer in it, but the problem is I don't have any knowledge with networking. I'm trying to create a server with ENet using external IP and random allocated port (maybe). Without any further chit-chat, let's jump to the code. I'm going to post the server only. First one is the main.lua and the second one is the thread.lua.
Code: Select all
local function split(string, delimiter)
local strings = {}
for string in string:gmatch("[^" .. delimiter .. "]+") do
strings[#strings + 1] = string
end
return strings
end
local ip, port
local thread
local channel
local time, cancel
local host
function love.load()
require "enet"
port = select(2, unpack(split(enet.host_create():get_socket_address(), ":")))
thread = love.thread.newThread("thread.lua")
channel = {
ip = love.thread.getChannel("ip_ip"),
request = love.thread.getChannel("ip_request")
}
time = 0
thread:start(true)
end
function love.update(dt)
if (not ip and not cancel) then
if (time < 5) then
time = time + dt
ip = channel.ip:pop()
if (ip) then
host = enet.host_create(ip .. ":" .. port)
end
else
cancel = true
channel.request:push(true)
end
end
end
function love.draw()
love.graphics.print("IP address: " .. (ip or "unknown"), 10, 10)
love.graphics.print("Internal port: " .. (port or "unknown"), 10, 24)
if (host) then
love.graphics.print("Server state: available", 10, 38)
else
love.graphics.print("Server state: unavailable", 10, 38)
end
end
Code: Select all
local http = require "socket.http"
local channel = {
ip = love.thread.getChannel("ip_ip"),
request = love.thread.getChannel("ip_request")
}
local ip, cancel
repeat
ip = http.request("http://myip.dnsomatic.com/")
cancel = channel.request:pop()
until (ip or cancel)
if (ip) then
channel.ip:supply(ip)
end