Lua 服务器与客户端实例
===============================================================
服务器,main.lua
===============================================================
local socket = require ( "socket" )
local tcpServer = nil
--创建指定端口的tcp server
local function createTCPServer( port )
-- Create Socket
local tcpServerSocket , err = socket.tcp()
local backlog = 5
-- Check Socket
if tcpServerSocket == nil then
return nil , err
end
-- Allow Address Reuse
tcpServerSocket:setoption( "reuseaddr" , true )
-- Bind Socket
local res, err = tcpServerSocket:bind( "*" , port )
if res == nil then
return nil , err
end
-- Check Connection
res , err = tcpServerSocket:listen( backlog )
if res == nil then
return nil , err
end
-- Return Server
return tcpServerSocket
end
--接受来自客户端的连接,并保存在tcpClient
local tcpClient = nil
local function acceptClient()
tcpServer:settimeout( 0 )
clientIn , _ = tcpServer:accept()
if clientIn then
tcpClient = clientIn
end
end
--接收已连接的客户端(tcpClient)数据
local function receiveLoop()
if tcpClient ~= nil then
local tcpClientMessage , _ = tcpClient:receive('*l')
if ( tcpClientMessage ~= nil ) then
print(tcpClientMessage)
tcpClient:send( "back:" .. tcpClientMessage .. "\n")
end
end
end
local function main()
tcpServer , _ = createTCPServer( 8080 )
if tcpServer then
Runtime:addEventListener( "enterFrame" , acceptClient )
Runtime:addEventListener( "enterFrame" , receiveLoop )
end
end
main()
===============================================================
客户端程序,main.lua
===============================================================
local socket = require("socket")
local tcpClient = nil
--接收来自服务器的数据
local function receiveData()
if tcpClient then
tcpClient:settimeout(0)
local msg = tcpClient:receive("*l")
if msg then
print(msg)
end
end
end
--向服务器发送数据
local index = 0
local function btnListener(event)
index = index + 1
if tcpClient then
tcpClient:send("pack index:" .. index .. ".\n")
end
end
--初始化
local function main()
local btn = ui.newButton{
default = "buttonBlue.png",
over = "buttonBlueOver.png",
onRelease = btnListener,
id = "btn"
}
btn:setReferencePoint(display.TopLeftReferencePoint)
btn.x = 10
btn.y = 100
--创建tcp连接
tcpClient = socket.tcp()
if tcpClient then
local ret = tcpClient:connect("192.168.1.2", 8080)
if ret then
tcpClient:send("hi, server, i'm client.\n")
Runtime:addEventListener("enterFrame", receiveData)
end
end
end
main()
lua socket相关文档参见:http://w3.impa.br/~diego/software/luasocket/tcp.html