1. -- Demo for Lua extension 'lqt'
  2. -- This demo shows how to create a QTcpServer (via Lingo and LuaDirector xtra)
  3.  
  4. require 'qtcore'
  5. require 'qtgui'
  6. require 'qtnetwork'
  7.  
  8. local server = 0
  9. local sockets = {}
  10. local app = QApplication(0,{})
  11.  
  12. ----------------------------------------
  13. -- prints received data to message window
  14. ----------------------------------------
  15. function printSocketData(n)
  16.   local socket = sockets[n]
  17.   while not socket:atEnd() do
  18.     data = socket:read(1024)
  19.     write(data)
  20.   end
  21. end
  22.  
  23. ----------------------------------------
  24. -- Lua function accesible as global function in Lingo
  25. ----------------------------------------
  26. on.startTcpServer = function(host, port)
  27.   if host==nil then host = '127.0.0.1' end
  28.   if port==nil then port = 12345 end
  29.  
  30.   server = QTcpServer()
  31.  
  32.   local ok = server:listen(QHostAddress(host), port)
  33.   if not ok then
  34.     write('\r> Error: Could not start TCP Server (host='..host..', port='..port..')\r')
  35.     return
  36.   end
  37.  
  38.   -- slot called whenever a new TCP connection was made
  39.   server:connect('2newConnection()', function()
  40.     write('\r> Notice: new TCP connection\r')
  41.  
  42.     local socket = server:nextPendingConnection()
  43.  
  44.     -- show hello message to connected client
  45.     socket:write('Welcome to the LuaDirector QTcpServer\r\n')
  46.  
  47.     local n = #sockets+1
  48.     local func = 'readyRead'..n..'()'
  49.     app:__addmethod(func, function()
  50.       printSocketData(n)
  51.     end)
  52.     socket:connect('2readyRead()', app, '1'..func)
  53.  
  54.     -- add to table of open sockets
  55.     sockets[n] = socket
  56.   end)
  57.  
  58.   write('\r> Notice: TCP Server started (host='..host..', port='..port..')\r')
  59. end
  60.  
  61. ----------------------------------------
  62. -- Lua function accesible as global function in Lingo
  63. ----------------------------------------
  64. on.stopTcpServer = function()
  65.   write('\r> Notice: TCP Server stopped\r')
  66.  
  67.   -- close all open sockets
  68.   for _,v in ipairs(sockets) do v:close() end
  69.   sockets = {}
  70.  
  71.   -- close the server
  72.   if server~=0 then
  73.     server:close()
  74.     server = 0
  75.   end
  76. end
  77.  
[raw code]