由于項(xiàng)目要換成全Lua的,所以趁這個機(jī)會研究了下LuaSocket和Lua Loop
Lua Loop: http://loop.luaforge.net/
LuaSocket: http://www.tecgraf.puc-rio.br/~diego/professional/luasocket/
感覺用這個寫個簡單的聊天服務(wù)器,或者寫個文字Mud的網(wǎng)絡(luò)小游戲挺方便的,而且上手容易,適合一些策劃做些自己想法的東西。Lua Loop我就不做介紹了,上面網(wǎng)站例子有很多。下面兩段便是用Lua寫的個服務(wù)器和客戶端的示例代碼:
運(yùn)行很簡單,只要將LuaSocket放在下面代碼說在的路徑,然后用lua5.0運(yùn)行。
1 -- server端Lua代碼
2
3 socket = require("socket");
4 host = host or "localhost";
5 port = port or "8383";
6 server = assert(socket.bind(host, port, 1000))
7 server:settimeout( 0 )
8
9 local client = {}
10 print("server: waiting for client connection
")
11 local clientcount = 0
12 while 1 do
13 control = server:accept()
14
15 if control ~= nil then
16 client[control] = control
17 clientcount = clientcount + 1
18 print( "有新客戶端連入鏈接總數(shù)為:" .. clientcount .. "\n" )
19 end
20
21
22 for user in pairs( client ) do
23 command = user:receive();
24 if command ~= nil then
25 print( command )
26 end
27 end
28
29 end
1 -- Client端Lua代碼
2 local MaxLink = 220
3 local socket = require("socket")
4 local c = {}
5
6 host = host or "localhost"
7 port = port or 8383
8 if arg then
9 host = arg[1] or host
10 port = arg[2] or port
11 end
12 print("Attempting connection to host '" ..host.. "' and port " ..port.. "
")
13 for i = 1, MaxLink do
14 c[i] = assert(socket.connect(host, port))
15 c[i]:settimeout( 0 )
16 end
17
18 print("Connected! Please type stuff (empty line to stop):")
19 l = io.read()
20 for i = 1, MaxLink do
21 assert( c[i]:send(l .. "\n") )
22 assert( c[i]:send("test" .. i .. "\n") )
23 print( "test" .. i .. "\n" )
24 end
25
26 while 1 do
27 for i = 1, MaxLink do
28 command = c[i]:receive()
29 if command ~= nil then
30 print(command)
31 end
32 end
33 end
34