2013-04-17 11 views
5

私はLuaプログラミング言語を使ってサーバを書いています。ネットワーク層はLuaSocketに基づいています。luasocketライブラリでソケットが閉じているかどうかチェックするには?

ソケットを検出する方法が見つからない、またはリファレンスマニュアルでデータを読み取ろうとする以外の方法が見つかりません(呼び出し時にnilおよびstring 'close'を返します)。

私のコードは次のようになります。それからデータを読み取ろうによって除く

local socket = require 'socket' 
local server = socket.tcp() 
local port = 9527 

server:bind('*', port) 
local status, errorMessage = server:listen() 
if status == 1 then 
    printf('Server is launched successfully on port %u', port) 
else 
    printf('Server listen failed, error message is %s', errorMessage) 
    return 
end 

local sockets = {server} 

while true do 
    local results = socket.select(sockets) 
    for _, sock in ipairs(results) do 
     if sock == server then 
      local s = server:accept() 

      callback('Connected', s) 
      table.insert(sockets, s) 

      printf('%s connected', s:getsockname()) 
     else 
      -- trying to detect socket is closed 
      if sock:isClosed() then 
       callback('Disconnected', sock) 

       for i, s in ipairs(sockets) do 
        if s == sock then 
         table.remove(sockets, i) 
         break 
        end 
       end 

       printf('%s disconnected', sock:getsockname()) 
      else 
       callback('ReadyRead', sock) 
      end 
     end 
    end 
end 
+0

'while true'ループの中で' server:settimeout'を呼び出します。 – hjpotter92

答えて

1

(それがnilと、文字列「閉じる」という呼び出しが返されます)。

私は他の方法について知らない。ソケットを読み取った結果をチェックするのがなぜあなたのために機能しないのですか?

settimeoutを使用してコールを非ブロッキングにし、closedcloseではない)のエラーをチェックする必要があります。 1バイトを読み取って保存することも、0バイトを読み取ることもできます。

関連する問題