mudgangster

Log | Files | Refs

connect.lua (1894B)


      1 local DataHandler
      2 
      3 local LastAddress
      4 local LastPort
      5 
      6 local loop = ev.Loop.default
      7 
      8 function mud.disconnect()
      9 	if not mud.connected then
     10 		mud.print( "\n#s> You're not connected..." )
     11 
     12 		return
     13 	end
     14 
     15 	mud.connected = false
     16 
     17 	mud.kill()
     18 end
     19 
     20 function mud.connect( address, port )
     21 	if mud.connected then
     22 		mud.print( "\n#s> Already connected! (%s:%d)", LastAddress, LastPort )
     23 
     24 		return
     25 	end
     26 
     27 	if not address then
     28 		if not LastAddress then
     29 			mud.print( "\n#s> I need an address..." )
     30 			
     31 			return
     32 		end
     33 
     34 		address = LastAddress
     35 		port = LastPort
     36 	end
     37 
     38 	local sock = socket.tcp()
     39 	sock:settimeout( 0 )
     40 	sock:connect( address, port )
     41 
     42 	mud.print( "\n#s> Connecting to %s:%d...", address, port )
     43 
     44 	mud.connected = true
     45 	mud.lastInput = mud.now()
     46 
     47 	mud.send = function( data )
     48 		mud.lastInput = mud.now()
     49 
     50 		sock:send( data )
     51 	end
     52 
     53 	mud.kill = function()
     54 		sock:shutdown()
     55 	end
     56 
     57 	ev.IO.new( function( loop, watcher )
     58 		local _, err = sock:receive( "*a" )
     59 
     60 		if err ~= "connection refused" then
     61 			LastAddress = address
     62 			LastPort = port
     63 
     64 			ev.IO.new( function( loop, watcher )
     65 				local _, err, data = sock:receive( "*a" )
     66 
     67 				if not data then
     68 					data = _
     69 				end
     70 				
     71 				if data then
     72 					DataHandler( data )
     73 					mud.handleXEvents()
     74 				end
     75 				
     76 				if err == "closed" then
     77 					mud.print( "\n#s> Disconnected!" )
     78 
     79 					watcher:stop( loop )
     80 					sock:shutdown()
     81 
     82 					mud.connected = false
     83 
     84 					return
     85 				end
     86 			end, sock:getfd(), ev.READ ):start( loop )
     87 		else
     88 			mud.print( "\n#s> Refused!" )
     89 
     90 			mud.connected = false
     91 		end
     92 
     93 		watcher:stop( loop )
     94 	end, sock:getfd(), ev.WRITE ):start( loop )
     95 end
     96 
     97 mud.alias( "/con", {
     98 	[ "^$" ] = function()
     99 		mud.connect()
    100 	end,
    101 
    102 	[ "^(%S+)%s+(%d+)$" ] = function( address, port )
    103 		mud.connect( address, port )
    104 	end,
    105 }, "<ip> <port>" )
    106 
    107 mud.alias( "/dc", mud.disconnect )
    108 
    109 return {
    110 	init = function( dataHandler )
    111 		DataHandler = dataHandler
    112 	end,
    113 }