summaryrefslogtreecommitdiff
path: root/tests/modules/socket/sched_tcp/echo_server.lua
blob: bb9cedd08cc513d2ed2a835724eaf616364e57ec (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import("core.base.bytes")
import("core.base.socket")
import("core.base.scheduler")

function _session_recv(sock)
    print("%s: recv ..", sock)
    local count = 0
    local result = nil
    local buff = bytes(8192)
    while count < 100000 do
        local recv, data = sock:recv(buff, 13, {block = true})
        if recv > 0 then
            result = data
            count = count + 1
        else
            break
        end
    end
    print("%s: recv ok, count: %d!", sock, count)
    if result then
        result:dump()
    end
end

function _session_send(sock)
    print("%s: send ..", sock)
    local count = 0
    while count < 100000 do
        local send = sock:send("hello world..", {block = true})
        if send > 0 then
            count = count + 1
        else
            break
        end
    end
    print("%s: send ok, count: %d!", sock, count)
end

function _listen(addr, port)

    local sock_clients = {}
    local sock = socket.bind(addr, port)
    sock:listen(100)
    print("%s: listening %s:%d ..", sock, addr, port)
    while true do
        local sock_client = sock:accept()
        if sock_client then
            print("%s: accepted", sock_client)
            table.insert(sock_clients, sock_client)
            sock_client:ctrl(socket.CTRL_SET_SENDBUFF, 6000000)
            sock_client:ctrl(socket.CTRL_SET_RECVBUFF, 6000000)
            scheduler.co_start(_session_recv, sock_client)
            scheduler.co_start(_session_send, sock_client)
        end
    end
    for _, sock_client in ipairs(sock_clients) do
        sock_client:close()
    end
    sock:close()
end

function main()
    scheduler.co_start(_listen, "127.0.0.1", 9091)
end