瀏覽代碼

Make result of connect() synchronous socket, and set up its metatable correctly

See issue #745
__gc (lsp_sock_gc) was not called at all.
As the TODO: in "mod_lua.inl" says, redesigning is a more desirable way.
This only corrects the inconsistency with the document.
xtne6f 6 年之前
父節點
當前提交
bc3d4af22e
共有 2 個文件被更改,包括 10 次插入7 次删除
  1. 5 4
      docs/UserManual.md
  2. 5 3
      src/mod_lua.inl

+ 5 - 4
docs/UserManual.md

@@ -826,17 +826,18 @@ connect (function):
     -- of simple socket interface. It returns a socket object with three
     -- methods: send, recv, close, which are synchronous (blocking).
     -- connect() throws an exception on connection error.
+    -- use_ssl is not implemented.
     connect(host, port, use_ssl)
 
     -- Example of using connect() interface:
-    local host = 'code.google.com'  -- IP address or domain name
-    local ok, sock = pcall(connect, host, 80, 1)
+    local host = 'www.example.com'  -- IP address or domain name
+    local ok, sock = pcall(connect, host, 80, 0)
     if ok then
-      sock:send('GET /p/civetweb/ HTTP/1.0\r\n' ..
+      sock:send('GET / HTTP/1.0\r\n' ..
                 'Host: ' .. host .. '\r\n\r\n')
       local reply = sock:recv()
       sock:close()
-      -- reply now contains the web page https://code.google.com/p/civetweb
+      -- reply now contains the web page http://www.example.com/
     end
 
 

+ 5 - 3
src/mod_lua.inl

@@ -327,6 +327,7 @@ lsp_connect(lua_State *L)
 		if (!ok) {
 			return luaL_error(L, ebuf);
 		} else {
+			set_blocking_mode(sock);
 			lua_newtable(L);
 			reg_lstring(L, "sock", (const char *)&sock, sizeof(SOCKET));
 			reg_string(L, "host", lua_tostring(L, -4));
@@ -2134,9 +2135,10 @@ prepare_lua_environment(struct mg_context *ctx,
 	 * TODO: Redesign the interface.
 	 */
 	luaL_newmetatable(L, LUASOCKET);
-	lua_pushliteral(L, "__index");
-	luaL_newlib(L, luasocket_methods);
-	lua_rawset(L, -3);
+	/* self.__index = self */
+	lua_pushvalue(L, -1);
+	lua_setfield(L, -2, "__index");
+	luaL_setfuncs(L, luasocket_methods, 0);
 	lua_pop(L, 1);
 	lua_register(L, "connect", lsp_connect);
 #endif