Modules/Sockets/sockOpen: Difference between revisions

From Multi Theft Auto: Wiki
Jump to navigation Jump to search
(Created page with '__NOTOC__ {{ModuleFunction|Sockets}} This function creates a socket. ==Syntax== <syntaxhighlight lang="lua"> socket sockOpen ( string hostname, int port) </syntaxhighlight> ===Required arguments=== * '''…')
 
Line 55: Line 55:


==See also==
==See also==
{{Modules/Sockets/Functions}}

Revision as of 13:47, 25 April 2010


Package-x-generic.png This function is provided by the external module Sockets. You must install this module to use this function.

This function creates a socket.

Syntax

socket sockOpen ( string hostname, int port)

Required arguments

  • hostname: The DNS or IP to connect to e.g. "www.google.com"
  • port: The port to bind the socket to e.g. 80

Returns

Returns userdata that represents the socket if you correct arguments were given, false otherwise.

Example

This piece of code connects to irc.gtanet.com, joins #mta and quits in 10 seconds.

local root = getRootElement()
local ircSocket = sockOpen("irc.gtanet.com")

addEventHandler("onSockOpened",root,
   function (socket)
      if socket == ircSocket then
         sockWrite(socket,"USER mta mta * MCvarial & Gamesnert")
         sockWrite(socket,"NICK mta")
         sockWrite(socket,"JOIN #mta")

         outputServerLog("IRC: Connected!")
         setTimer(disconnect,10000,1)
      end
   end
)

addEventHandler("onSockData",root,
   function (socket,data)
      if socket == ircSocket then
         outputServerLog(data)
      end
   end
)

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

function disconnect ()
   sockClose(ircSocket)
end

See also