Skip to content

Instantly share code, notes, and snippets.

@cloudwu
Created May 18, 2016 10:51
Show Gist options
  • Save cloudwu/9ba552ed9bc87a34f8051e84a6ea0731 to your computer and use it in GitHub Desktop.
Save cloudwu/9ba552ed9bc87a34f8051e84a6ea0731 to your computer and use it in GitHub Desktop.
skynet socket transfor
local skynet = require "skynet"
local socket = require "socket"
local mode , id = ...
local function echo(id)
socket.start(id)
skynet.error("start", id)
while true do
local str = socket.read(id)
if str then
socket.write(id, str)
if str:match "^trans" then
skynet.error("transfor to new service")
socket.abandon(id)
break
end
else
socket.close(id)
return
end
end
end
if mode == "agent" then
id = tonumber(id)
skynet.start(function()
skynet.fork(function()
if pcall(echo,id) then
skynet.newservice(SERVICE_NAME, "agent", id)
end
skynet.exit()
end)
end)
else
local function accept(id)
socket.start(id)
socket.write(id, "Hello Skynet\n")
skynet.newservice(SERVICE_NAME, "agent", id)
-- notice: Some data on this connection(id) may lost before new service start.
-- So, be careful when you want to use start / abandon / start .
socket.abandon(id)
end
skynet.start(function()
local id = socket.listen("127.0.0.1", 8001)
print("Listen socket :", "127.0.0.1", 8001)
socket.start(id , function(id, addr)
print("connect from " .. addr .. " " .. id)
-- you have choices :
-- 1. skynet.newservice("testsocket", "agent", id)
-- 2. skynet.fork(echo, id)
-- 3. accept(id)
accept(id)
end)
end)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment