Template:Modules/Sockets/Functions: Difference between revisions

From Multi Theft Auto: Wiki
Jump to navigation Jump to search
Line 14: Line 14:


==Example==
==Example==
This example shows you how you can connect to irc.
This example shows you how you can connect to irc for 10 seconds.


'''PHP:''' (for the page that LUA expects to be at ''<nowiki>http://www.example.com/page.php</nowiki>'')
'''PHP:''' (for the page that LUA expects to be at ''<nowiki>http://www.example.com/page.php</nowiki>'')
Line 25: Line 25:
         sockWrite(socket,"USER IRCbot botname * :Gamesnert & MCvarial")
         sockWrite(socket,"USER IRCbot botname * :Gamesnert & MCvarial")
         sockWrite(socket,"NICK botname")
         sockWrite(socket,"NICK botname")
        sockWrite(socket,"JOIN #mta")
        setTimer(disconnect,10000,1)
       end
       end
   end
   end
)
)
addEventHandler("onSockData",getRootElement(),
  function (sock,data)
      if sock == socket then
        outputServerLog("IRC: "..data)
      end
  end
)
addEventHandler("onSockClosed",getRootElement(),
  function (sock)
      if sock == socket then
        outputServerLog("IRC: disconnected!")
      end
  end
)
function disconnect ()
  sockClose(socket)
  socket = nil
end
</syntaxhighlight>
</syntaxhighlight>



Revision as of 13:18, 25 April 2010

This function creates a socket.

Syntax

userdata sockOpen ( string host, int port )

Required Arguments

  • host: This is a host name e.g. "www.google.com"
  • port: This is the port on which to connect e.g. 80

Returns

Returns userdata if the correct arguments were given false otherwise.

Example

This example shows you how you can connect to irc for 10 seconds.

PHP: (for the page that LUA expects to be at http://www.example.com/page.php)

local socket = sockOpen("irc.gtanet.com",80)

addEventHandler("onSockOpened",getRootElement(),
   function (sock)
      if sock == socket then
         sockWrite(socket,"USER IRCbot botname * :Gamesnert & MCvarial")
         sockWrite(socket,"NICK botname")
         sockWrite(socket,"JOIN #mta")

         setTimer(disconnect,10000,1)
      end
   end
)

addEventHandler("onSockData",getRootElement(),
   function (sock,data)
      if sock == socket then
         outputServerLog("IRC: "..data)
      end
   end
)

addEventHandler("onSockClosed",getRootElement(),
   function (sock)
      if sock == socket then
         outputServerLog("IRC: disconnected!")
      end
   end
)

function disconnect ()
  sockClose(socket)
  socket = nil
end


Important Note: Sockets are asynchronous this means if sockOpen() returns the socket isn't actually created!

See Also