Mercurial > hg > Members > nobuyasu > Lua
changeset 9:ddac6199c51a default tip
Added echo_server_select.lua
author | Nobuyasu Oshiro <dimolto@cr.ie.u-ryukyu.ac.jp> |
---|---|
date | Sun, 09 Mar 2014 02:30:37 +0900 |
parents | b5ce185f154b |
children | |
files | coroutine/echo_server/echo_server_select.lua |
diffstat | 1 files changed, 50 insertions(+), 0 deletions(-) [+] |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/coroutine/echo_server/echo_server_select.lua Sun Mar 09 02:30:37 2014 +0900 @@ -0,0 +1,50 @@ +local socket = require("socket") + +response = { ["end"] = function(sock) sock:close() end} + +function acceptfunction(server, time) + acceptco = coroutine.create( + function (serversocket, time) + time = time or 0.1 + serversocket:settimeout(time) + coroutine.yield(serversocket:accept()) + end) + return coroutine.resume(acceptco, server, time) +end +function echofunction(socketarray) + echoco = coroutine.create( + function(socketarray, time) + time = time or 0.1 + if #socketarray == 0 then + socket.select(nil, nil, time) + coroutine.yield() + end + local canread = socket.select(socketarray, socketarray, time) + for _,c in ipairs(canread) do + local mess, err = c:receive() + if response[mess] then + response[mess](c) + else + print(mess) + c:send(mess.."\n") + end + end + coroutine.yield() + end ) + return coroutine.resume(echoco, socketarray, 0.1) +end + +local socketarray = {} +local server = socket.bind("127.0.0.1", "8080") +assert(server) +while true do + local flag, socket = acceptfunction(server, 0.1) + if socket then + table.insert(socketarray, socket) + end + echofunction(socketarray) +end + + + +