Server(It's a lua script but it won't work on love itself):
Code: Select all
socket = require("socket")
function newset()
local reverse = {}
local set = {}
return setmetatable(set, {__index = {
insert = function(set, value)
if not reverse[value] then
table.insert(set, value)
reverse[value] = table.getn(set)
end
end,
remove = function(set, value)
local index = reverse[value]
if index then
reverse[value] = nil
local top = table.remove(set)
if top ~= value then
reverse[top] = index
set[index] = top
end
end
end
}})
end
-- set socket
server = socket.bind("*", 12345)
server:settimeout(0)
-- create new set
set = newset()
-- insert server socket to set
while true do
local client = server:accept()
-- accept new connection
if client ~= nil then
set:insert(client)
print("New client connected!! ".. client:getpeername())
client:send("Hello!\n")
end
-- recieve from client
for a = 1, #set do
local readdata, err = set[a]:receive()
if err then
print("Client disconnected: " .. set[a]:getpeername() .. " Reason: " .. err)
set[a]:close()
set:remove(set[a])
else
if readdata ~= nil then
local peer = set[a]:getpeername()
print("[" .. peer .. "]: " .. readdata)
end
end
end
end
Code: Select all
local socket = require "socket"
local timer = 0
function love.load()
client = socket.connect("127.0.0.1", 12345)
if client == nil then
print("Couldn't connect to server...")
else
client:settimeout(0)
print("Connected to server! " .. client:getpeername())
end
end
function love.update(dt)
if client ~= nil then
local data_recv, err = client:receive()
if data_recv ~= nil then
print("Server sent a data: " .. data_recv)
else
if err ~= "timeout" then
print("Oops. Something happened: " .. err)
client:close()
client = nil
end
end
-- once in a 3 secs, send "Hi!\n" to server
timer = timer + dt
if timer >= 3 then
timer = timer - 3
client:send("Hi!\n")
print("Send data to server: Hi!")
end
end
end
The problem is: when I terminate server script with Ctrl+C with proper interrupt, client displays "Oops. Something happened: closed" properly. But when I terminate server without proper interrupt(like killing server process directly), client doesn't recognize as server closed and trying to keep sending data for every 3 seconds - which I don't want to do.
I checked luasocket reference manual, but I don't see any function can check socket's status (check if socket is connected or disconencted) / ping other side to check if connection is available / etc. How can I check if connection is available or not?