lua-users home
lua-l archive

cosockets for beginners

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hello,
After much sleepless nights staring at Messieurs Carregal and Guerra's Copas library... I finally gathered enough courage to devise my own concoction :) It basically does pretty the same thing as Copas, but in a much more verbose way :P Here is a short example to illustrate the implementation of a dumb 'echo' server:
-- Start the server on port number 2000
SocketServer.new( "*", 2000, aDelegate ).start()
-- Start the run loop
SocketRunLoop.default().run()
The server implementation is handled by the delegate's run() method, which gets invoked when a client connect to the server:
 this.run = function( aTask, aServer, aReader, aWriter )
 while ( true ) do
 local aValue = aReader.read()
 if ( aValue ~= nil ) then
aWriter.writeln( "echo: " .. string.format( "%q", aValue ) )
 if ( aValue == "quit" ) then
aWriter.writeln( "echo: byebye" )
 aReader.close()
 break
 end
 end
 aTask.yield()
 end
 end
The 4 parameters to the run() method are as fellow:
- 'aTask' represents the coroutine the method is running in.
- 'aServer' represents the server which invoked this delegate.
- 'aReader' is an asynchronous wrapper around socket:receive().
- 'aWriter' is an asynchronous wrapper around socket:send().
That's pretty much it.
Gory details bellow:
http://dev.alt.textdrive.com/file/lu/SocketServer.lua
http://dev.alt.textdrive.com/file/lu/SocketRunLoop.lua
http://dev.alt.textdrive.com/file/lu/SocketTask.lua
http://dev.alt.textdrive.com/file/lu/SocketReader.lua
http://dev.alt.textdrive.com/file/lu/SocketWriter.lua
Comments, opinions, slappings warmly welcome :)
Cheers
--
PA, Onnay Equitursay
http://alt.textdrive.com/

AltStyle によって変換されたページ (->オリジナル) /