服务端:
#main
local skynet = require "skynet"
local function action()
skynet.uniqueservice("debug_console",8000)
skynet.uniqueservice "watchdog"
skynet.exit()
end
skynet.start(action)
#wachdog
local skynet = require "skynet"
local socket = require "socket"
skynet.start(function()
local id = socket.listen("",8080,1024)
socket.start(id,function(fd,addr)
local agent = skynet.newservice "agent"
skynet.send(agent,"lua","SOCKET",fd,addr)
socket.abandon(fd)
end)
end)
#agent
local skynet = require "skynet"
local socket = require "socket"
local CMD = {}
-- 模拟信号矢量
local signal = true
-- 心跳超时次数
local timeval = 0
--解包函数
local function unpack_data(package)
-- 收到的包总长度
local total_len = string.len(package)
print("总大小为:",total_len)
-- 解包格式
local fmt = string.format(">Ic%d",string.len(package) - string.packsize(">I"))
--解包后的数组
local tmp_pkg = {}
while 1 do
-- 开始解包
local endpoint, subpkg, _ = string.unpack(fmt,package)
-- 截断字符串
tmp_data = subpkg:sub(1,endpoint)
-- 插入到临时表中
table.insert(tmp_pkg,tmp_data)
-- 得到剩余包的内容
--package = string.gsub(package,string.sub(package,begin,endpoint + string.packsize(">I")),"")
package = package:sub(1+endpoint+string.packsize(">I"),#package)
-- 重置fmt格式
fmt = string.format(">Ic%d",package:len() - string.packsize(">I"))
if #package <= 0 then
break
end
end
--打印一下看是否解包正确
for k,v in pairs(tmp_pkg) do
print(k,v)
end
return tmp_pkg
end
local function heartbeat(fd)
-- 15秒后无回应即断开客户端回收资源
while 1 do
if timeval >=5 then
break
end
skynet.sleep(300)
timeval = timeval + 1
end
socket.close(fd)
skynet.error("客户端链接超时.....")
skynet.exit()
end
function CMD.SOCKET(fd,addr)
socket.start(fd)
--skynet.fork(heartbeat,fd)
while true do
local data = socket.read(fd)
if not data then
--读到EOF表示关闭了套接字。
socket.close(fd)
break
end
timeval = 0
profile.start()
local pb_arr = unpack_data(data)
local time = profile.stop()
skynet.error(time)
end
skynet.error("[",os.date("%c",os.time()),"],","client ",addr,"close this session.")
skynet.exit()
end
skynet.start(function()
skynet.dispatch("lua",function(_,_,cmd,...)
local func = assert(CMD[cmd])
if type(func) == "function" then
func(...)
end
end)
end)
客户端:
#main.py
#!/usr/bin/python2.7
#encoding:utf-8
from gevent import socket
import struct,message_pb2
s = socket.socket()
s.connect(("192.168.40.2",8080))
while 1:
data = raw_input("Please input Something:\n>>")
pkg1 = struct.pack(">I%ds" %(len(data)),len(data),data)
pkg2 = struct.pack(">I%ds" %(len("Nancy")),len("Nancy"),"Nancy")
pkg3 = struct.pack(">I%ds" %(len("Michael")),len("Michael"),"Michael")
s.send(pkg1 + pkg2 + pkg3)
print(pkg1,pkg2,pkg3)
print(pkg1 + pkg2 + pkg3)
s.close()