lua中配置luasocket,並且做成一個socket伺服器,主要用於(D'Fusion Studio)中
如圖所示:
在你的工程中需要加入lua資料夾,mime資料夾,socket資料夾,我的開發工具主要是D'Fusion Studio,主要用來做增強現實的。我把它們放到我的工程的lib資料夾中。
直接就是我做的一個監聽伺服器,上程式碼如下,這樣我們在來慢慢說需要注意的地方:
local scriptPath = getScriptDirectory() LOG(scriptPath) local lua_cpath1 = scriptPath.."lib\\?.dll" --路徑設定是一定要是這樣設定,否則會出現錯誤,要不在查詢“socket.core"出現錯誤 local lua_path1 = scriptPath.."lib\\lua\\?.lua;"..scriptPath.."lib\\lua\\socket\\?.lua" --LOG(package.cpath) --LOG("\n\n") --LOG(package.path) package.path = package.path ..";"..lua_path1 package.cpath = package.cpath ..";"..lua_cpath1 local socket = require('socket') LOG("Socket Version: "..socket._VERSION) local port = 8885 local server = assert(socket.bind("192.168.110.82",port)) local i,p = server:getsockname() server:settimeout(0)--設定超時時間為0,這樣就可以為非阻塞 assert(i, p) LOG("Waiting connection from talker on " .. i .. ":" .. p .. "...") local client = {} local clientCount = 0 repeat --LOG("START") --server:settimeout(0) local c = server:accept() coroutine.yield() --coroutine.yield() if c then local clientStr = c:getpeername() LOG("Connected. Here is the stuff:"..clientStr) clientCount = clientCount+1 client[clientCount] = c LOG("clientCount:"..clientCount) end --coroutine.yield() --coroutine.yield() for n,user in pairs(client) do --LOG("n = "..n) user:settimeout(0)--需要這一個 local l, e = user:receive() if l then LOG(l)--列印l傳送過來的值 e為錯誤資訊 local recStr = "Receiveing:"..l text:setText(recStr) if e then LOG("value = "..e ) end end end until coroutine.yield()
需要注意的地方:
1、環境變數配置。我在這直接更改的lua的執行環境變數。
local lua_cpath1 = scriptPath.."lib\\?.dll" --路徑設定是一定要是這樣設定,否則會出現錯誤,要不在查詢“socket.core"出現錯誤
local lua_path1 = scriptPath.."lib\\lua\\?.lua;"..scriptPath.."lib\\lua\\socket\\?.lua"
package.path = package.path ..";"..lua_path1
package.cpath = package.cpath ..";"..lua_cpath1
要特別注意配置dll路徑的時候,必須要配置成scriptPath.."lib\\?.dll" ,"<scriptPath>\lib\"中放著luasocket的3個資料夾,只有這樣配置才能執行成功,因為在socket.lua檔案中有一個require(“socket.core"),當呼叫它時,它就會自動的到<scriptPath>\lib\socket\core.dll中查詢相關的函式。如果對這部分不懂的話,查詢相關require的用法。
2、server:settimeout(0)與user:settimeout(0),設定這一部分之後,程式就會成為非阻塞的。
3、最為重要的,當客戶端像此伺服器傳送訊息的時候,傳送的文字必須以'\n'結束