我的lua是5.1 luasocket是2.0.1 环境是centos5.8
VMware建立3台centos虚拟机,我是把一台的搭建好后,copy了一下,注意启动copy的os时会提示让你选择当前系统是copy or move,一定要选择copy。
首先需要确定你的linux是否支持多播,看一下/boot下的config文件,这个网上有许多资料指导。
开启路由:
route add -net 224.0.0.0 netmask 240.0.0.0 dev eth0
写luasocket的哥们是个高手,压缩包里不但有源码,还有很多lua的例子,看得我云里雾里的,还需要进步啊。
代码如下:
client:
- local dispatch = require("dispatch")
- local handler = dispatch.newhandler()
- local socket = require("socket")
- host = host or "224.0.0.89"
- port = port or 8899
- if arg then
- host = arg[1] or host
- port = arg[2] or port
- end
- --host = socket.dns.toip(host)
- udp = assert(socket.udp())
- --assert(udp:setpeername(host, port))
- assert(udp:setsockname(host, port))
- print("Using remote host '" ..host.. "' and port " .. port .. "...")
- --assert(udp:setoption("ip-multicast-loop",true))
- assert(udp:setoption("ip-multicast-loop",false))
- assert(udp:setoption("ip-add-membership",{multiaddr=host,interface="*"}))
- while 1 do
- dgram, pip, pport = udp:receivefrom()
- --dgram = assert(udp:receive())
- print("recv data : " ..dgram.." from " ..pip.." : "..pport)
- print(">> ")
- end
server:
- local dispatch = require("dispatch")
- local handler = dispatch.newhandler()
- local socket = require("socket")
- host = host or "224.0.0.89"
- port = port or 8899
- if arg then
- host = arg[1] or host
- port = arg[2] or port
- end
- --host = socket.dns.toip(host)
- udp = assert(socket.udp())
- assert(udp:setpeername(host, port))
- print("Using remote host '" ..host.. "' and port " .. port .. "...")
- assert(udp:setoption("ip-multicast-loop",true))
- assert(udp:setoption("ip-add-membership",{multiaddr=host,interface="*"}))
- while 1 do
- print(">> ")
- line = io.read()
- if not line or line == "" then
- assert(udp:setoption("ip-drop-membership",{multiaddr=host,interface="*"}))
- os.exit()
- end
- assert(udp:send(line))
- end
dispatch是luasocket里面自带的一个库,负责调度,代码正在看。
阅读(1845) | 评论(0) | 转发(0) |