aboutsummaryrefslogtreecommitdiff
path: root/src/lua/modules/net/je_lua_net.cpp
blob: 58ece43e47d497f6c8b49a69e8bafdddcf3c2501 (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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include "lua/modules/luax.h"
#include "lua/modules/types.h"
#include "libjin/jin.h"
#include "lua/common/je_lua_common.h"
#include "je_lua_buffer.h"

namespace JinEngine
{
namespace Lua
{

    using namespace JinEngine::Lua::Net;
	using namespace JinEngine::Net;

    LUA_IMPLEMENT int l_initNetwork(lua_State* L)
    {
        JinEngine::Net::NetManager::get()->init();
        return 1;
    }
    
    LUA_IMPLEMENT int l_Socket(lua_State* L)
    {
        SocketInformation info = { 0 };
        {
            const char* socketType = luax_checkstring(L, 1);
            if (strcmp(socketType, "TCP") == 0)
                info.type = SocketType::TCP;
            else if (strcmp(socketType, "UDP") == 0)
                info.type = SocketType::UDP;
            else
            {
                luax_error(L, "jin.net.Socket() first paramter wrong, must be TCP or UDP");
                return 0;
            }
            // type, port
            if (luax_gettop(L) == 2)
            {
                info.port = luax_checkinteger(L, 2);
            }
            // type, address, port
            else if (luax_gettop(L) == 3)
            {
                if (luax_isstringstrict(L, 2))
                    info.address = tk_strtohl(luax_checkstring(L, 2));
                else if (luax_isintegerstrict(L, 2))
                    info.address = luax_checkinteger(L, 2);
                info.port = luax_checkinteger(L, 3);
            }
        }
        Socket* socket = new Socket(info);
        Proxy* proxy = luax_newinstance(L, JIN_NETWORK_SOCKET);
        proxy->bind(new Shared<Socket>(socket, JIN_NETWORK_SOCKET));
        return 1;
    }

    LUA_IMPLEMENT int l_Buffer(lua_State* L)
    {
        int size = luax_checkinteger(L, 1);
        Proxy* proxy = luax_newinstance(L, JIN_NETWORK_BUFFER);
        Net::Buffer* buffer = new Net::Buffer(size);
        proxy->bind(new Shared<Buffer>(buffer, JIN_NETWORK_BUFFER));
        return 1;
    }

    LUA_IMPLEMENT const luaL_Reg f[] = {
        { "init",      l_initNetwork },
        { "newSocket", l_Socket      },
        { "newBuffer", l_Buffer      },
        { 0,           0             }
    };

    LUA_PORT int luaopen_Socket(lua_State* L);
    LUA_PORT int luaopen_Buffer(lua_State* L);

    LUA_EXPORT int luaopen_net(lua_State* L)
    {
        luaopen_Socket(L);
        luaopen_Buffer(L);

        luax_newlib(L, f);

        return 1;
    }

} // namespace Lua
} // namespace JinEngine