static int luasocket_new1(lua_State *L){ luaRef_t obj = toluaRef(L,1); int domain = lua_tointeger(L,2); int type = lua_tointeger(L,3); luasocket_t luasock; handle_t sock; if(type == SOCK_STREAM){ sock = kn_new_sock(domain,type,IPPROTO_TCP); if(!sock){ lua_pushnil(L); return 1; } luasock = calloc(1,sizeof(*luasock)); luasock->type = _SOCKET; kn_sock_setud(sock,luasock); }else if(type == SOCK_DGRAM){ uint32_t recvbuf_size = lua_tointeger(L,4); decoder* _decoder = (decoder*)lua_touserdata(L,5); luasock = calloc(1,sizeof(*luasock)); luasock->datagram = new_datagram(domain,recvbuf_size,_decoder); luasock->type = _DATAGRAM; sock = datagram_gethandle(luasock->datagram); datagram_setud(luasock->datagram,luasock,destroy_luasocket); datagram_associate(g_engine,luasock->datagram,on_datagram); }else{ lua_pushnil(L); return 1; } luasock->sock = sock; luasock->luaObj = obj; lua_pushlightuserdata(L,luasock); return 1; }
static int luasocket_connect(lua_State *L){ luasocket_t luasock = lua_touserdata(L,1); if(luasock->type != _SOCKET){ lua_pushstring(L,"invaild socket"); return 1; } if(!luaL_checkstring(L,2)){ lua_pushstring(L,"invalid ip"); return 1; } if(!luaL_checkinteger(L,3)){ lua_pushstring(L,"invalid port"); return 1; } const char *ip = lua_tostring(L,2); int port = lua_tointeger(L,3); kn_sockaddr host; kn_addr_init_in(&host,ip,port); int ret = kn_sock_connect(luasock->sock,&host,NULL); if(ret > 0){ lua_pushnil(L); lua_pushinteger(L,ret); }else if(ret == 0){ kn_engine_associate(g_engine,luasock->sock,cb_connect); lua_pushnil(L); lua_pushinteger(L,ret); }else{ lua_pushstring(L,"connect error"); lua_pushnil(L); } kn_sock_setud(luasock->sock,luasock); return 2; }
static int luasocket_new2(lua_State *L){ luaRef_t obj = toluaRef(L,1); handle_t sock = lua_touserdata(L,2); luasocket_t luasock = calloc(1,sizeof(*luasock)); luasock->type = _SOCKET; luasock->sock = sock; luasock->luaObj = obj; kn_sock_setud(sock,luasock); lua_pushlightuserdata(L,luasock); return 1; }
void on_accept(handle_t s,void *ud){ printf("on_accept\n"); engine_t p = (engine_t)ud; struct session *session = calloc(1,sizeof(*session)); session->s = s; kn_sock_setud(s,session); kn_sock_associate(s,p,transfer_finish,NULL); session_recv(session); ++client_count; printf("%d\n",client_count); }