天字一号

泠泠七弦上 静听松风寒 古调虽自爱 今人多不弹

   :: 首页 :: 联系 ::  :: 管理
  4 Posts :: 0 Stories :: 3 Comments :: 0 Trackbacks

常用链接

留言簿(1)

我参与的团队

最新评论

阅读排行榜

由于项目要换成全Lua的,所以趁这个机会研究了下LuaSocket和Lua Loop
Lua Loop: http://loop.luaforge.net/
LuaSocket: http://www.tecgraf.puc-rio.br/~diego/professional/luasocket/
感觉用这个写个简单的聊天服务器,或者写个文字Mud的网络小游戏挺方便的,而且上手容易,适合一些策划做些自己想法的东西。Lua Loop我就不做介绍了,上面网站例子有很多。下面两段便是用Lua写的个服务器和客户端的示例代码:
运行很简单,只要将LuaSocket放在下面代码说在的路径,然后用lua5.0运行。

 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( "有新客户端连入链接总数为:" .. 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 = 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 
posted on 2009-03-23 20:12 Wizard 阅读(2920) 评论(1)  编辑 收藏 引用

Feedback

# re: 用Lua写个轻量级服务器 2009-04-26 01:05 shongbee2
先膜拜一下!然后再看。呵呵。  回复  更多评论
  


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理