Friday, December 19, 2008

Copas做客户端的用法

Copas的文档确实不是很全.如果想用Copas来写一个主动发起连接的程序怎么写呢?

function handler()
client=socket.tcp()
client:connect('127.0.0.1',10009)
co_socket=copas.wrap(client)
co_socket:settimeout(120)
print('connect to '..client:getpeername())
while true do
local data=co_socket:receive('*l')
if not data then
break
else
if data~='' then print('recv:'..data) end
if data:find('xxx') then

end
end

end

end

end

copas.addthread(handler)
copas.loop()
显然,copas.addthread()是核心.这个函数,接收一个函数,并将之创建为协程.
接下来,在copas的tick中,调度这个协程.如果,addthread()的参数不止一个,多余的参数会被传给协程.
但要注意的是,会在参数列表头部多出一个nil的参数.