【问题标题】:How to run blocking operation in Corona SDK Lua?如何在 Corona SDK Lua 中运行阻塞操作?
【发布时间】:2013-01-07 20:02:24
【问题描述】:

我是 LUA 新手,我正在使用 Corona SDK 在 LUA 中编写一个 tcp 消息传递库。我遇到了一个问题,即套接字读取操作即使在协程中运行也会挂起应用程序 UI。

我如何启动协程:

function Messaging:readLoop()
   self.readCoroutine = coroutine.create(function() self:blockingLoop() end)
   coroutine.resume(self.readCoroutine)
end

阻塞循环:

function Messaging:blockingLoop()
   line,err,rest = self.sock:receive(BUFSIZE) -- <= Hangs UI if there is no incoming data 
end

当然我知道协程不等于线程,但我希望 LUA 解释器在阻塞操作时切换到另一个协程(例如带有 GIL 的 Python 线程)。 是否有可能在不阻塞 UI 的情况下从套接字读取?例如使用真正的线程或异步方法?谢谢。

附:消除 BUFSIZ 不是选项,因为我根本不想阻止 UI,即使是 0.2..0.4 秒(移动网络延迟慢)

【问题讨论】:

    标签: sockets asynchronous tcp lua coroutine


    【解决方案1】:

    Corona contains LuaSockets 可以让您进行异步套接字通信,如 here 所示。

    【讨论】:

      【解决方案2】:

      Corona 有一个用于异步调用的 network.request API..

      如果您不想使用它,请查看this asynchronous http library

      【讨论】:

      • 不幸的是,它会发出 HTTP 请求,但我需要直接使用套接字。
      • 第二个链接呢?我没有彻底了解它,但它似乎在使用套接字连接..
      • 第二个的源代码确实包含异步解决方法,谢谢。我将尝试使用它来编译更多或更少的工作。
      【解决方案3】:

      根据 MudSatheeshJM 发布的链接,我终于制作了一个可能对某人有所帮助的消息传递类

      -- Messaging prototype
      Messaging = {sock = nil, sockTimer = nil}
      
      -- Messaging constructor
      function Messaging:new (o)
         o = o or {}
         setmetatable(o, self)
         self.__index = self
         return o
      end
      
      function Messaging:connect()
         self.sock = socket.tcp()
         print( self.sock:connect(HOST, PORT) )
         self.sock:settimeout(0)
         self.sockTimer = timer.performWithDelay(50, function() self:checkData() end, 0)
      end
      
      function Messaging:close()
         timer.cancel(self.sockTimer)
         self.sock:close()
      end
      
      function Messaging:checkData()
         local data, status, rest = self.sock:receive()
         local s
         if data then
            s = data
         else
            s = rest
         end
         if s:len() ~= 0 then
            print ('received', s)
         end
      end
      

      重要提示:

      1. self.sock:settimeout(0) 需要使套接字非阻塞
      2. local data, status, rest = self.sock:receive()

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-06-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-08
        • 2013-07-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多