Advertisement
Guest User

Untitled

a guest
Sep 23rd, 2012
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 68.11 KB | None | 0 0
  1. /*! TheGood
  2. AHKsock - A simple AHK implementation of Winsock.
  3. http://www.autohotkey.com/forum/viewtopic.php?p=355775
  4. Last updated: January 19, 2011
  5.  
  6. FUNCTION LIST:
  7.  
  8. ________________________________________
  9. AHKsock_Listen(sPort, sFunction = False)
  10.  
  11. Tells AHKsock to listen on the port in sPort, and call the function in sFunction when events occur. If sPort is a port on
  12. which AHKsock is already listening, the action taken depends on sFunction:
  13. - If sFunction is False, AHKsock will stop listening on the port in sPort.
  14. - If sFunction is "()", AHKsock will return the name of the current function AHKsock calls when
  15. a client connects on the port in sPort.
  16. - If sFunction is a valid function, AHKsock will set that function as the new function to call
  17. when a client connects on the port in sPort.
  18.  
  19. Returns blank on success. On failure, it returns one of the following positive integer:
  20. 2: sFunction is not a valid function.
  21. 3: The WSAStartup() call failed. The error is in ErrorLevel.
  22. 4: The Winsock DLL does not support version 2.2.
  23. 5: The getaddrinfo() call failed. The error is in ErrorLevel.
  24. 6: The socket() call failed. The error is in ErrorLevel.
  25. 7: The bind() call failed. The error is in ErrorLevel.
  26. 8: The WSAAsyncSelect() call failed. The error is in ErrorLevel.
  27. 9: The listen() call failed. The error is in ErrorLevel.
  28.  
  29. For the failures which affect ErrorLevel, ErrorLevel will contain either the reason the DllCall itself failed (ie. -1, -2,
  30. An, etc... as laid out in the AHK docs for DllCall) or the Windows Sockets Error Code as defined at:
  31. http://msdn.microsoft.com/en-us/library/ms740668
  32.  
  33. See the section titled "STRUCTURE OF THE EVENT-HANDLING FUNCTION AND MORE INFO ABOUT SOCKETS" for more info about how the
  34. function in sFunction interacts with AHKsock.
  35.  
  36. ________________________________________
  37. AHKsock_Connect(sName, sPort, sFunction)
  38.  
  39. Tells AHKsock to connect to the hostname or IP address in sName on the port in sPort, and call the function in sFunction
  40. when events occur.
  41.  
  42. Although the function will return right away, the connection attempt will still be in progress. Once the connection attempt
  43. is over, successful or not, sFunction will receive the CONNECTED event. Note that it is important that once AHKsock_Connect
  44. returns, the current thread must stay (or soon after must become) interruptible so that sFunction can be called once the
  45. connection attempt is over.
  46.  
  47. AHKsock_Connect can only be called again once the previous connection attempt is over. To check if AHKsock_Connect is ready
  48. to make another connection attempt, you may keep polling it by calling AHKsock_Connect(0,0,0) until it returns False.
  49.  
  50. Returns blank on success. On failure, it returns one of the following positive integer:
  51. 1: AHKsock_Connect is still processing a connection attempt. ErrorLevel contains the name and the port of that
  52. connection attempt, separated by a tab.
  53. 2: sFunction is not a valid function.
  54. 3: The WSAStartup() call failed. The error is in ErrorLevel.
  55. 4: The Winsock DLL does not support version 2.2.
  56. 5: The getaddrinfo() call failed. The error is in ErrorLevel.
  57. 6: The socket() call failed. The error is in ErrorLevel.
  58. 7: The WSAAsyncSelect() call failed. The error is in ErrorLevel.
  59. 8: The connect() call failed. The error is in ErrorLevel.
  60.  
  61. For the failures which affect ErrorLevel, ErrorLevel will contain either the reason the DllCall itself failed (ie. -1, -2,
  62. An, etc... as laid out in the AHK docs for DllCall) or the Windows Sockets Error Code as defined at:
  63. http://msdn.microsoft.com/en-us/library/ms740668
  64.  
  65. See the section titled "STRUCTURE OF THE EVENT-HANDLING FUNCTION AND MORE INFO ABOUT SOCKETS" for more info about how the
  66. function in sFunction interacts with AHKsock.
  67.  
  68. _______________________________________
  69. AHKsock_Send(iSocket, ptrData, iLength)
  70.  
  71. Sends the data of length iLength to which ptrData points to the connected socket in iSocket.
  72.  
  73. Returns the number of bytes sent on success. This can be less than the number requested to be sent in the iLength parameter,
  74. i.e. between 1 and iLength. This would occur if no buffer space is available within the transport system to hold the data to
  75. be transmitted, in which case the number of bytes sent can be between 1 and the requested length, depending on buffer
  76. availability on both the client and server computers. On failure, it returns one of the following negative integer:
  77. -1: WSAStartup hasn't been called yet.
  78. -2: Received WSAEWOULDBLOCK. This means that calling send() would have blocked the thread.
  79. -3: The send() call failed. The error is in ErrorLevel.
  80. -4: The socket specified in iSocket is not a valid socket. This means either that the socket in iSocket hasn't been
  81. created using AHKsock_Connect or AHKsock_Listen, or that the socket has already been destroyed.
  82. -5: The socket specified in iSocket is not cleared for sending. You haven't waited for the SEND event before calling,
  83. either ever, or not since you last received WSAEWOULDBLOCK.
  84.  
  85. You may start sending data to the connected socket in iSocket only after the socket's associated function receives the first
  86. SEND event. Upon receiving the event, you may keep calling AHKsock_Send to send data until you receive the error -2, at
  87. which point you must wait once again until you receive another SEND event before sending more data. Not waiting for the SEND
  88. event results in receiving error -5 when calling AHKsock_Send.
  89.  
  90. For the failures which affect ErrorLevel, ErrorLevel will contain either the reason the DllCall itself failed (ie. -1, -2,
  91. An, etc... as laid out in the AHK docs for DllCall) or the Windows Sockets Error Code as defined at:
  92. http://msdn.microsoft.com/en-us/library/ms740668
  93.  
  94. ____________________________________________
  95. AHKsock_ForceSend(iSocket, ptrData, iLength)
  96.  
  97. This function is exactly the same as AHKsock_Send, but with three differences:
  98. - If only part of the data could be sent, it will automatically keep trying to send the remaining part.
  99. - If it receives WSAEWOULDBLOCK, it will wait for the socket's SEND event and try sending the data again.
  100. - If the data buffer to send is larger than the socket's send buffer size, it will automatically send the data in
  101. smaller chunks in order to avoid a performance hit. See http://support.microsoft.com/kb/823764 for more info.
  102.  
  103. Therefore, AHKsock_ForceSend will return only when all the data has been sent. Because this function relies on waiting for
  104. the socket's SEND event before continuing to send data, it cannot be called in a critical thread. Also, for the same reason,
  105. it cannot be called from a socket's associated function (not specifically iSocket's associated function, but any socket's
  106. associated function).
  107.  
  108. Another limitation to consider when choosing between AHKsock_Send and AHKsock_ForceSend is that AHKsock_ForceSend will not
  109. return until all the data has been sent (unless an error occurs). Although the script will still be responsive (new threads
  110. will still be able to launch), the thread from which it was called will not resume until it returns. Therefore, if sending
  111. a large amount of data, you should either use AHKsock_Send, or use AHKsock_ForceSend by feeding it smaller pieces of the
  112. data, allowing you to update the GUI if necessary (e.g. a progress bar).
  113.  
  114. Returns blank on success, which means that all the data to which ptrData points of length iLength has been sent. On failure,
  115. it returns one of the following negative integer:
  116. -1: WSAStartup hasn't been called yet.
  117. -3: The send() call failed. The error is in ErrorLevel.
  118. -4: The socket specified in iSocket is not a valid socket. This means either that the socket in iSocket hasn't been
  119. created using AHKsock_Connect or AHKsock_Listen, or that the socket has already been destroyed.
  120. -5: The current thread is critical.
  121. -6: The getsockopt() call failed. The error is in ErrorLevel.
  122.  
  123. For the failures which affect ErrorLevel, ErrorLevel will contain either the reason the DllCall itself failed (ie. -1, -2,
  124. An, etc... as laid out in the AHK docs for DllCall) or the Windows Sockets Error Code as defined at:
  125. http://msdn.microsoft.com/en-us/library/ms740668
  126.  
  127. ____________________________________________
  128. AHKsock_Close(iSocket = -1, iTimeout = 5000)
  129.  
  130. Closes the socket in iSocket. If no socket is specified, AHKsock_Close will close all the sockets on record, as well as
  131. terminate use of the Winsock 2 DLL (by calling WSACleanup). If graceful shutdown cannot be attained after the timeout
  132. specified in iTimeout (in milliseconds), it will perform a hard shutdown before calling WSACleanup to free resources. See
  133. the section titled "NOTES ON CLOSING SOCKETS AND AHKsock_Close" for more information.
  134.  
  135. Returns blank on success. On failure, it returns one of the following positive integer:
  136. 1: The shutdown() call failed. The error is in ErrorLevel. AHKsock_Close forcefully closed the socket and freed the
  137. associated resources.
  138.  
  139. Note that when AHKsock_Close is called with no socket specified, it will never return an error.
  140.  
  141. For the failures which affect ErrorLevel, ErrorLevel will contain either the reason the DllCall itself failed (ie. -1, -2,
  142. An, etc... as laid out in the AHK docs for DllCall) or the Windows Sockets Error Code as defined at:
  143. http://msdn.microsoft.com/en-us/library/ms740668
  144.  
  145. ___________________________________________________________
  146. AHKsock_GetAddrInfo(sHostName, ByRef sIPList, bOne = False)
  147.  
  148. Retrieves the list of IP addresses that correspond to the hostname in sHostName. The list is contained in sIPList, delimited
  149. by newline characters. If bOne is True, only one IP (the first one) will be returned.
  150.  
  151. Returns blank on success. On failure, it returns one of the following positive integer:
  152. 1: The WSAStartup() call failed. The error is in ErrorLevel.
  153. 2: The Winsock DLL does not support version 2.2.
  154. 3: Received WSAHOST_NOT_FOUND. No such host is known.
  155. 4: The getaddrinfo() call failed. The error is in ErrorLevel.
  156.  
  157. For the failures which affect ErrorLevel, ErrorLevel will contain either the reason the DllCall itself failed (ie. -1, -2,
  158. An, etc... as laid out in the AHK docs for DllCall) or the Windows Sockets Error Code as defined at:
  159. http://msdn.microsoft.com/en-us/library/ms740668
  160.  
  161. _________________________________________________________________________
  162. AHKsock_GetNameInfo(sIP, ByRef sHostName, sPort = 0, ByRef sService = "")
  163.  
  164. Retrieves the hostname that corresponds to the IP address in sIP. If a port in sPort is supplied, it also retrieves the
  165. service that corresponds to the port in sPort.
  166.  
  167. Returns blank on success. On failure, it returns on of the following positive integer:
  168. 1: The WSAStartup() call failed. The error is in ErrorLevel.
  169. 2: The Winsock DLL does not support version 2.2.
  170. 3: The IP address supplied in sIP is invalid.
  171. 4: The getnameinfo() call failed. The error is in ErrorLevel.
  172.  
  173. For the failures which affect ErrorLevel, ErrorLevel will contain either the reason the DllCall itself failed (ie. -1, -2,
  174. An, etc... as laid out in the AHK docs for DllCall) or the Windows Sockets Error Code as defined at:
  175. http://msdn.microsoft.com/en-us/library/ms740668
  176.  
  177. ______________________________________________
  178. AHKsock_SockOpt(iSocket, sOption, iValue = -1)
  179.  
  180. Retrieves or sets a socket option. Supported options are:
  181. SO_KEEPALIVE: Enable/Disable sending keep-alives. iValue must be True/False to enable/disable. Disabled by default.
  182. SO_SNDBUF: Total buffer space reserved for sends. Set iValue to 0 to completely disable the buffer. Default is 8 KB.
  183. SO_RCVBUF: Total buffer space reserved for receives. Default is 8 KB.
  184. TCP_NODELAY: Enable/Disable the Nagle algorithm for send coalescing. Set iValue to True to disable the Nagle algorithm,
  185. set iValue to False to enable the Nagle algorithm, which is the default.
  186.  
  187. It is usually best to leave these options to their default (especially the Nagle algorithm). Only change them if you
  188. understand the consequences. See MSDN for more information on those options.
  189.  
  190. If iValue is specified, it sets the option to iValue and returns blank on success. If iValue is left as -1, it returns the
  191. value of the option specified. On failure, it returns one of the following negative integer:
  192. -1: The getsockopt() failed. The error is in ErrorLevel.
  193. -2: The setsockopt() failed. The error is in ErrorLevel.
  194.  
  195. For the failures which affect ErrorLevel, ErrorLevel will contain either the reason the DllCall itself failed (ie. -1, -2,
  196. An, etc... as laid out in the AHK docs for DllCall) or the Windows Sockets Error Code as defined at:
  197. http://msdn.microsoft.com/en-us/library/ms740668
  198.  
  199. _______________________________________
  200. AHKsock_Settings(sSetting, sValue = "")
  201.  
  202. Changes the AHKsock setting in sSetting to sValue. If sValue is blank, the current value for that setting is returned. If
  203. sValue is the word "Reset", the setting is restored to its default value. The possible settings are:
  204. Message: Determines the Windows message numbers used to monitor network events. The message number in iMessage and the
  205. next number will be used. Default value is 0x8000. For example, calling AHKsock_Settings("Message", 0x8005)
  206. will cause AHKsock to use 0x8005 and 0x8006 to monitor network events.
  207. Buffer: Determines the size of the buffer (in bytes) used when receiving data. This is thus the maximum size of bData
  208. when the RECEIVED event is raised. If the data received is more than the buffer size, multiple recv() calls
  209. (and thus multiple RECEIVED events) will be needed. Note that you shouldn't use this setting as a means of
  210. delimiting frames. See the "NOTES ON RECEIVING AND SENDING DATA" section for more information about receiving
  211. and sending data. Default value is 64 KB, which is the maximum for TCP.
  212.  
  213. If you do call AHKsock_Settings to change the values from their default ones, it is best to do so at the beginning of the
  214. script. The message number used cannot be changed as long as there are active connections.
  215.  
  216. ______________________________________
  217. AHKsock_ErrorHandler(sFunction = """")
  218.  
  219. Sets the function in sFunction to be the new error handler. If sFunction is left at its default value, it returns the name
  220. of the current error handling function.
  221.  
  222. An error-handling function is optional, but may be useful when troubleshooting applications. The function will be called
  223. anytime there is an error that arises in a thread which wasn't called by the user but by the receival of a Windows message
  224. which was registered using OnMessage.
  225.  
  226. The function in sFunction must be of the following format:
  227. MyErrorHandler(iError, iSocket)
  228.  
  229. The possible values for iError are:
  230. 1: The connect() call failed. The error is in ErrorLevel.
  231. 2: The WSAAsyncSelect() call failed. The error is in ErrorLevel.
  232. 3: The socket() call failed. The error is in ErrorLevel.
  233. 4: The WSAAsyncSelect() call failed. The error is in ErrorLevel.
  234. 5: The connect() call failed. The error is in ErrorLevel.
  235. 6: FD_READ event received with an error. The error is in ErrorLevel. The socket is in iSocket.
  236. 7: The recv() call failed. The error is in ErrorLevel. The socket is in iSocket.
  237. 8: FD_WRITE event received with an error. The error is in ErrorLevel. The socket is in iSocket.
  238. 9: FD_ACCEPT event received with an error. The error is in ErrorLevel. The socket is in iSocket.
  239. 10: The accept() call failed. The error is in ErrorLevel. The listening socket is in iSocket.
  240. 11: The WSAAsyncSelect() call failed. The error is in ErrorLevel. The listening socket is in iSocket.
  241. 12: The listen() call failed. The error is in ErrorLevel. The listening socket is in iSocket.
  242. 13: The shutdown() call failed. The error is in ErrorLevel. The socket is in iSocket.
  243.  
  244. For the failures which affect ErrorLevel, ErrorLevel will contain either the reason the DllCall itself failed (ie. -1, -2,
  245. An, etc... as laid out in the AHK docs for DllCall) or the Windows Sockets Error Code as defined at:
  246. http://msdn.microsoft.com/en-us/library/ms740668
  247.  
  248. __________________________________________________________________
  249. NOTES ON SOCKETS AND THE STRUCTURE OF THE EVENT-HANDLING FUNCTION:
  250.  
  251. The functions used in the sFunction parameter of AHKsock_Listen and AHKsock_Connect must be of the following format:
  252.  
  253. MyFunction(sEvent, iSocket = 0, sName = 0, sAddr = 0, sPort = 0, ByRef bData = 0, bDataLength = 0)
  254.  
  255. The variable sEvent contains the event for which MyFunction was called. The event raised is associated with one and only one
  256. socket; the one in iSocket. The meaning of the possible events that can occur depend on the type of socket involved. AHKsock
  257. deals with three different types of sockets:
  258. - Listening sockets: These sockets are created by a call to AHKsock_Listen. All they do is wait for clients to request
  259. a connection. These sockets will never appear as the iSocket parameter because requests for connections are
  260. immediately accepted, and MyFunction immediately receives the ACCEPTED event with iSocket set to the accepted socket.
  261. - Accepted sockets: These sockets are created once a listening socket receives an incoming connection attempt from a
  262. client and accepts it. They are thus the sockets that servers use to communicate with clients.
  263. - Connected sockets: These sockets are created by a successful call to AHKsock_Connect. These are the sockets that
  264. clients use to communicate with servers.
  265.  
  266. More info about sockets:
  267. - You may have multiple client sockets connecting to the same listening socket (ie. on the same port).
  268. - You may have multiple listening sockets for different ports.
  269. - You cannot have more than one listening socket for the same port (or you will receive a bind() error).
  270. - Every single connection between a client and a server will have its own client socket on the client side, and its own
  271. server (accepted) socket on the server side.
  272.  
  273. For all of the events that the event-handling function receives,
  274. - sEvent contains the event that occurred (as described below),
  275. - iSocket contains the socket on which the event occurred,
  276. - sName contains a value which depends on the type of socket in iSocket:
  277. - If the socket is an accepted socket, sName is empty.
  278. - If the socket is a connected socket, sName is the same value as the sName parameter that was used when
  279. AHKsock_Connect was called to create the socket. Since AHKsock_Connect accepts both hostnames and IP addresses,
  280. sName may contain either.
  281. - sAddr contains the IP address of the socket's endpoint (i.e. the peer's IP address). This means that if the socket in
  282. iSocket is an accepted socket, sAddr contains the IP address of the client. Conversely, if it is a connected socket,
  283. sAddr contains the server's IP.
  284. - sPort contains the server port on which the connection was accepted.
  285.  
  286. Obviously, if your script only calls AHKsock_Listen (acting as a server) or AHKsock_Connect (acting as a client) you don't
  287. need to check if the socket in iSocket is an accepted socket or a connected socket, since it can only be one or the other.
  288. But if you do call both AHKsock_Listen and AHKsock_Connect with both of them using the same function (e.g. MyFunction), then
  289. you will need to check what type of socket iSocket is by checking the sName parameter.
  290.  
  291. Of course, it would be easier to simply have two different functions, for example, MyFunction1 and MyFunction2, with one
  292. handling the server part and the other handling the client part so that you don't need to check what type of socket iSocket
  293. is when each function is called. However, this might not be necessary if both server and client are "symmetrical" (i.e. the
  294. conversation doesn't actually change whether or not we're on the server side or the client side). See Example 3 for an
  295. example of this, where only one function is used for both server and client sockets.
  296.  
  297. The variable sEvent can be one of the following values if iSocket is an accepted socket:
  298. sEvent = Event Description:
  299. ACCEPTED A client connection was accepted (see the "Listening sockets" section above for more details).
  300. CONNECTED <Does not occur on accepted sockets>
  301. DISCONNECTED The client disconnected (see AHKsock_Close for more details).
  302. SEND You may now send data to the client (see AHKsock_Send for more details).
  303. RECEIVED You received data from the client. The data received is in bData and the length is in bDataLength.
  304. SENDLAST The client is disconnecting. This is your last chance to send data to it. Once this function returns,
  305. disconnection will occur. This event only occurs on the side which did not initiate shutdown (see
  306. AHKsock_Close for more details).
  307.  
  308. The variable sEvent can be one of the following values if iSocket is a connected socket:
  309. sEvent = Event Description:
  310. ACCEPTED <Does not occur on connected sockets>
  311. CONNECTED The connection attempt initiated by calling AHKsock_Connect has completed (see AHKsock_Connect for more
  312. details). If it was successful, iSocket will equal the client socket. If it failed, iSocket will equal -1.
  313. To get the error code that the failure returned, set an error handling function with AHKsock_ErrorHandler,
  314. and read ErrorLevel when iError is equal to 1.
  315. DISCONNECTED The server disconnected (see AHKsock_Close for more details).
  316. SEND You may now send data to the server (see AHKsock_Send for more details).
  317. RECEIVED You received data from the server. The data received is in bData and the length is in bDataLength.
  318. SENDLAST The server is disconnecting. This is your last chance to send data to it. Once this function returns,
  319. disconnection will occur. This event only occurs on the side which did not initiate shutdown (see
  320. AHKsock_Close for more details).
  321.  
  322. More information: The event-handling functions described in here are always called with the Critical setting on. This is
  323. necessary in order to ensure proper processing of messages. Note that as long as the event-handling function does not
  324. return, AHKsock cannot process other network messages. Although messages are buffered, smooth operation might suffer when
  325. letting the function run for longer than it should.
  326.  
  327. ___________________________________________
  328. NOTES ON CLOSING SOCKETS AND AHKsock_Close:
  329.  
  330. There are a few things to note about the AHKsock_Close function. The most important one is this: because the OnExit
  331. subroutine cannot be made interruptible if running due to a call to Exit/ExitApp, AHKsock_Close will not be able to execute
  332. a graceful shutdown if it is called from there.
  333.  
  334. A graceful shutdown refers to the proper way of closing a TCP connection. It consists of an exchange of special TCP messages
  335. between the two endpoints to acknowledge that the connection is about to close. It also fires the SENDLAST event in the
  336. socket's associated function to notify that this is the last chance it will have to send data before disconnection. Note
  337. that listening sockets cannot (and therefore do not need to) be gracefully shutdown as it is not an end-to-end connection.
  338. (In practice, you will never have to manually call AHKsock_Close on a listening socket because you do not have access to
  339. them. The socket is closed when you stop listening by calling AHKsock_Listen with no specified value for the second
  340. parameter.)
  341.  
  342. In order to allow the socket(s) connection(s) to gracefully shutdown (which is always preferable), AHKsock_Close must be
  343. called in a thread which is, or can be made, interruptible. If it is called with a specified socket in iSocket, it will
  344. initiate a graceful shutdown for that socket alone. If it is called with no socket specified, it will initiate a graceful
  345. shutdown for all connected/accepted sockets, and once done, deregister itself from the Windows Sockets implementation and
  346. allow the implementation to free any resources allocated for Winsock (by calling WSACleanup). In that case, if any
  347. subsequent AHKsock function is called, Winsock will automatically be restarted.
  348.  
  349. Therefore, before exiting your application, AHKsock_Close must be called at least once with no socket specified in order to
  350. free Winsock resources. This can be done in the OnExit subroutine, either if you do not wish to perform a graceful shutdown
  351. (which is not recommended), or if you have already gracefully shutdown all the sockets individually before calling
  352. Exit/ExitApp. Of course, it doesn't have to be done in the OnExit subroutine and can be done anytime before (which is the
  353. recommended method because AHKsock will automatically gracefully shutdown all the sockets on record).
  354.  
  355. This behaviour has a few repercussions on your application's design. If the only way for the user to terminate your
  356. application is through AHK's default Exit menu item in the tray menu, then upon selecting the Exit menu item, the OnExit sub
  357. will fire, and your application will not have a chance to gracefully shutdown connected sockets. One way around this is to
  358. add your own menu item which will in turn call AHKsock_Close with no socket specified before calling ExitApp to enter the
  359. OnExit sub. See AHKsock Example 1 for an example of this.
  360.  
  361. This is how the graceful shutdown process occurs between two connected peers:
  362. a> Once one of the peers (it may be the server of the client) is done sending all its data, it calls AHKsock_Close to
  363. shutdown the socket. (It is not a good idea to have the last peer receiving data call AHKsock_Close. This will result
  364. in AHKsock_Send errors on the other peer if more data needs to be sent.) In the next steps, we refer to the peer that
  365. first calls AHKsock_Close as the invoker, and the other peer simply as the peer.
  366. b> The peer receives the invoker's intention to close the connection and is given one last chance to send any remaining
  367. data. This is when the peer's socket's associated function receives the SENDLAST event.
  368. c> Once the peer is done sending any remaining data (if any), it also calls AHKsock_Close on that same socket to shut it
  369. down, and then close the socket for good. This happens once the peer's function that received the SENDLAST event
  370. returns from the event. At this point, the peer's socket's associated function receives the DISCONNECTED event.
  371. d> This happens in parallel with c>. After the invoker receives the peer's final data (if any), as well as notice that
  372. the peer has also called AHKsock_Close on the socket, the invoker finally also closes the socket for good. At this
  373. point, the socket's associated function also receives the DISCONNECTED event.
  374.  
  375. When AHKsock_Close is called with no socket specified, this process occurs (in parallel) for every connected socket on
  376. record.
  377.  
  378. ____________________________________
  379. NOTES ON RECEIVING AND SENDING DATA:
  380.  
  381. It's important to understand that AHKsock uses the TCP protocol, which is a stream protocol. This means that the data
  382. received comes as a stream, with no apparent boundaries (i.e. frames or packets). For example, if a peer sends you a string,
  383. it's possible that half the string is received in one RECEIVED event and the other half is received in the next. Of course,
  384. the smaller the string, the less likely this happens. Conversely, the larger the string, the more likely this will occur.
  385.  
  386. Similarly, calling AHKsock_Send will not necessarily send the data right away. If multiple AHKsock_Send calls are issued,
  387. Winsock might, under certain conditions, wait and accumulate data to send before sending it all at once. This process is
  388. called coalescing. For example, if you send two strings to your peer by using two individual AHKsock_Send calls, the peer
  389. will not necessarily receive two consecutive RECEIVED events for each string, but might instead receive both strings through
  390. a single RECEIVED event.
  391.  
  392. One efficient method of receiving data as frames is to use length-prefixing. Length-prefixing means that before sending a
  393. frame of variable length to your peer, you first tell it how many bytes will be in the frame. This way, your peer can
  394. divide the received data into frames that can be individually processed. If it received less than a frame, it can store the
  395. received data and wait for the remaining data to arrive before processing the completed frame with the length specified.
  396. This technique is used in in AHKsock Example 3, where peers send each other strings by first declaring how long the string
  397. will be (see the StreamProcessor function of Example 3).
  398.  
  399. ____________________________________
  400. NOTES ON TESTING A STREAM PROCESSOR:
  401.  
  402. As you write applications that use length-prefixing as described above, you might find it hard to test their ability to
  403. properly cut up and/or put together the data into frames when testing them on the same machine or on a LAN (because the
  404. latency is too low and it is thus harder to stress the connection).
  405.  
  406. In this case, what you can do to properly test them is to uncomment the comment block in AHKsock_Send, which will sometimes
  407. purposely fail to send part of the data requested. This will allow you to simulate what could happen on a connection going
  408. through the Internet. You may change the probability of failure by changing the number in the If statement.
  409.  
  410. If your application can still work after uncommenting the block, then it is a sign that it is properly handling frames split
  411. across multiple RECEIVED events. This would also demonstrate your application's ability to cope with partially sent data.
  412. */
  413.  
  414. /****************\
  415. Main functions |
  416. */
  417.  
  418. AHKsock_Listen(sPort, sFunction = False) {
  419.  
  420. ;Check if there is already a socket listening on this port
  421. If (sktListen := AHKsock_Sockets("GetSocketFromNamePort", A_Space, sPort)) {
  422.  
  423. ;Check if we're stopping the listening
  424. If Not sFunction {
  425. AHKsock_Close(sktListen) ;Close the socket
  426.  
  427. ;Check if we're retrieving the current function
  428. } Else If (sFunction = "()") {
  429. Return AHKsock_Sockets("GetFunction", sktListen)
  430.  
  431. ;Check if it's a different function
  432. } Else If (sFunction <> AHKsock_Sockets("GetFunction", sktListen))
  433. AHKsock_Sockets("SetFunction", sktListen, sFunction) ;Update it
  434.  
  435. Return ;We're done
  436. }
  437.  
  438. ;Make sure we even have a function
  439. If Not IsFunc(sFunction)
  440. Return 2 ;sFunction is not a valid function.
  441.  
  442. ;Make sure Winsock has been started up
  443. If (i := AHKsock_Startup())
  444. Return (i = 1) ? 3 ;The WSAStartup() call failed. The error is in ErrorLevel.
  445. : 4 ;The Winsock DLL does not support version 2.2.
  446.  
  447. ;Resolve the local address and port to be used by the server
  448. VarSetCapacity(aiHints, 16 + 4 * A_PtrSize, 0)
  449. NumPut(1, aiHints, 0, "Int") ;ai_flags = AI_PASSIVE
  450. NumPut(2, aiHints, 4, "Int") ;ai_family = AF_INET
  451. NumPut(1, aiHints, 8, "Int") ;ai_socktype = SOCK_STREAM
  452. NumPut(6, aiHints, 12, "Int") ;ai_protocol = IPPROTO_TCP
  453. iResult := DllCall("Ws2_32\GetAddrInfo", "Ptr", 0, "Ptr", &sPort, "Ptr", &aiHints, "Ptr*", aiResult)
  454. If (iResult != 0) Or ErrorLevel { ;Check for error
  455. ErrorLevel := ErrorLevel ? ErrorLevel : iResult
  456. Return 5 ;The getaddrinfo() call failed. The error is in ErrorLevel.
  457. }
  458.  
  459. sktListen := -1 ;INVALID_SOCKET
  460. sktListen := DllCall("Ws2_32\socket", "Int", NumGet(aiResult+0, 04, "Int")
  461. , "Int", NumGet(aiResult+0, 08, "Int")
  462. , "Int", NumGet(aiResult+0, 12, "Int"), "Ptr")
  463. If (sktListen = -1) Or ErrorLevel { ;Check for INVALID_SOCKET
  464. sErrorLevel := ErrorLevel ? ErrorLevel : AHKsock_LastError()
  465. DllCall("Ws2_32\FreeAddrInfo", "Ptr", aiResult)
  466. ErrorLevel := sErrorLevel
  467. Return 6 ;The socket() call failed. The error is in ErrorLevel.
  468. }
  469.  
  470. ;Setup the TCP listening socket
  471. iResult := DllCall("Ws2_32\bind", "Ptr", sktListen, "Ptr", NumGet(aiResult+0, 16 + 2 * A_PtrSize), "Int", NumGet(aiResult+0, 16, "Ptr"))
  472. If (iResult = -1) Or ErrorLevel { ;Check for SOCKET_ERROR
  473. sErrorLevel := ErrorLevel ? ErrorLevel : AHKsock_LastError()
  474. DllCall("Ws2_32\closesocket", "Ptr", sktListen)
  475. DllCall("Ws2_32\FreeAddrInfo", "Ptr", aiResult)
  476. ErrorLevel := sErrorLevel
  477. Return 7 ;The bind() call failed. The error is in ErrorLevel.
  478. }
  479.  
  480. DllCall("Ws2_32\FreeAddrInfo", "Ptr", aiResult)
  481.  
  482. ;Add socket to array with A_Space for Name and IP to indicate that it's a listening socket
  483. AHKsock_Sockets("Add", sktListen, A_Space, A_Space, sPort, sFunction)
  484.  
  485. ;We must now actually register the socket
  486. If AHKsock_RegisterAsyncSelect(sktListen) {
  487. sErrorLevel := ErrorLevel
  488. DllCall("Ws2_32\closesocket", "Ptr", sktListen)
  489. AHKsock_Sockets("Delete", sktListen) ;Remove from array
  490. ErrorLevel := sErrorLevel
  491. Return 8 ;The WSAAsyncSelect() call failed. The error is in ErrorLevel.
  492. }
  493.  
  494. ;Start listening for incoming connections
  495. iResult := DllCall("Ws2_32\listen", "Ptr", sktListen, "Int", 0x7FFFFFFF) ;SOMAXCONN
  496. If (iResult = -1) Or ErrorLevel { ;Check for SOCKET_ERROR
  497. sErrorLevel := ErrorLevel ? ErrorLevel : AHKsock_LastError()
  498. DllCall("Ws2_32\closesocket", "Ptr", sktListen)
  499. AHKsock_Sockets("Delete", sktListen) ;Remove from array
  500. ErrorLevel := sErrorLevel
  501. Return 9 ;The listen() call failed. The error is in ErrorLevel.
  502. }
  503. }
  504.  
  505. AHKsock_Connect(sName, sPort, sFunction) {
  506. Static aiResult, iPointer, bProcessing, iMessage
  507. Static sCurName, sCurPort, sCurFunction, sktConnect
  508.  
  509. ;Check if it's just to inquire whether or not a call is possible
  510. If (Not sName And Not sPort And Not sFunction)
  511. Return bProcessing
  512.  
  513. ;Check if we're busy
  514. If bProcessing And (sFunction != iMessage) {
  515. ErrorLevel := sCurName A_Tab sCurPort
  516. Return 1 ;AHKsock_Connect is still processing a connection attempt. ErrorLevel contains the name and the port,
  517. ;delimited by a tab.
  518. } Else If bProcessing { ;sFunction = iMessage. The connect operation has finished.
  519.  
  520. ;Check if it was successful
  521. If (i := sPort >> 16) {
  522.  
  523. ;Close the socket that failed
  524. DllCall("Ws2_32\closesocket", "Ptr", sktConnect)
  525.  
  526. ;Get the next pointer. ai_next
  527. iPointer := NumGet(iPointer+0, 16 + 3 * A_PtrSize)
  528.  
  529. ;Check if we reached the end of the linked structs
  530. If (iPointer = 0) {
  531.  
  532. ;We can now free the chain of addrinfo structs
  533. DllCall("Ws2_32\FreeAddrInfo", "Ptr", aiResult)
  534.  
  535. ;This is to ensure that the user can call AHKsock_Connect() right away upon receiving the message.
  536. bProcessing := False
  537.  
  538. ;Raise an error (can't use Return 1 because we were called asynchronously)
  539. ErrorLevel := i
  540. AHKsock_RaiseError(1) ;The connect() call failed. The error is in ErrorLevel.
  541.  
  542. ;Call the function to signal that connection failed
  543. If IsFunc(sCurFunction)
  544. %sCurFunction%("CONNECTED", -1, sCurName, 0, sCurPort)
  545.  
  546. Return
  547. }
  548.  
  549. } Else { ;Successful connection!
  550.  
  551. ;Get the IP we successfully connected to
  552. sIP := DllCall("Ws2_32\inet_ntoa", "UInt", NumGet(NumGet(iPointer+0, 16 + 2 * A_PtrSize)+4, 0, "UInt"), "AStr")
  553.  
  554. ;We can now free the chain of ADDRINFO structs
  555. DllCall("Ws2_32\FreeAddrInfo", "Ptr", aiResult)
  556.  
  557. ;Add socket to array
  558. AHKsock_Sockets("Add", sktConnect, sCurName, sIP, sCurPort, sCurFunction)
  559.  
  560. ;This is to ensure that the user can call AHKsock_Connect() right away upon receiving the message.
  561. bProcessing := False
  562.  
  563. ;Do this small bit in Critical so that AHKsock_AsyncSelect doesn't receive
  564. ;any FD messages before we call the user function
  565. Critical
  566.  
  567. ;We must now actually register the socket
  568. If AHKsock_RegisterAsyncSelect(sktConnect) {
  569. sErrorLevel := ErrorLevel ? ErrorLevel : AHKsock_LastError()
  570. DllCall("Ws2_32\closesocket", "Ptr", sktConnect)
  571. AHKsock_Sockets("Delete", sktConnect) ;Remove from array
  572. ErrorLevel := sErrorLevel
  573. AHKsock_RaiseError(2) ;The WSAAsyncSelect() call failed. The error is in ErrorLevel.
  574.  
  575. If IsFunc(sCurFunction) ;Call the function to signal that connection failed
  576. %sCurFunction%("CONNECTED", -1, sCurName, 0, sCurPort)
  577.  
  578. } Else If IsFunc(sCurFunction) ;Call the function to signal that connection was successful
  579. %sCurFunction%("CONNECTED", sktConnect, sCurName, sIP, sCurPort)
  580.  
  581. Return
  582. }
  583.  
  584. } Else { ;We were called
  585.  
  586. ;Make sure we even have a function
  587. If Not IsFunc(sFunction)
  588. Return 2 ;sFunction is not a valid function.
  589.  
  590. bProcessing := True ;Block future calls to AHKsock_Connect() until we're done
  591.  
  592. ;Keep the values
  593. sCurName := sName
  594. sCurPort := sPort
  595. sCurFunction := sFunction
  596.  
  597. ;Make sure Winsock has been started up
  598. If (i := AHKsock_Startup()) {
  599. bProcessing := False
  600. Return (i = 1) ? 3 ;The WSAStartup() call failed. The error is in ErrorLevel.
  601. : 4 ;The Winsock DLL does not support version 2.2.
  602. }
  603.  
  604. ;Resolve the server address and port
  605. VarSetCapacity(aiHints, 16 + 4 * A_PtrSize, 0)
  606. NumPut(2, aiHints, 4, "Int") ;ai_family = AF_INET
  607. NumPut(1, aiHints, 8, "Int") ;ai_socktype = SOCK_STREAM
  608. NumPut(6, aiHints, 12, "Int") ;ai_protocol = IPPROTO_TCP
  609. iResult := DllCall("Ws2_32\GetAddrInfo", "Ptr", &sName, "Ptr", &sPort, "Ptr", &aiHints, "Ptr*", aiResult)
  610. If (iResult != 0) Or ErrorLevel { ;Check for error
  611. ErrorLevel := ErrorLevel ? ErrorLevel : iResult
  612. bProcessing := False
  613. Return 5 ;The getaddrinfo() call failed. The error is in ErrorLevel.
  614. }
  615.  
  616. ;Start with the first struct
  617. iPointer := aiResult
  618. }
  619.  
  620. ;Create a SOCKET for connecting to server
  621. sktConnect := DllCall("Ws2_32\socket", "Int", NumGet(iPointer+0, 04, "Int")
  622. , "Int", NumGet(iPointer+0, 08, "Int")
  623. , "Int", NumGet(iPointer+0, 12, "Int"), "Ptr")
  624. If (sktConnect = 0xFFFFFFFF) Or ErrorLevel { ;Check for INVALID_SOCKET
  625. sErrorLevel := ErrorLevel ? ErrorLevel : AHKsock_LastError()
  626. DllCall("Ws2_32\FreeAddrInfo", "Ptr", aiResult)
  627. bProcessing := False
  628. ErrorLevel := sErrorLevel
  629. If (sFunction = iMessage) { ;Check if we were called asynchronously
  630. AHKsock_RaiseError(3) ;The socket() call failed. The error is in ErrorLevel.
  631.  
  632. ;Call the function to signal that connection failed
  633. If IsFunc(sCurFunction)
  634. %sCurFunction%("CONNECTED", -1)
  635. }
  636. Return 6 ;The socket() call failed. The error is in ErrorLevel.
  637. }
  638.  
  639. ;Register the socket to know when the connect() function is done. FD_CONNECT = 16
  640. iMessage := AHKsock_Settings("Message") + 1
  641. If AHKsock_RegisterAsyncSelect(sktConnect, 16, "AHKsock_Connect", iMessage) {
  642. sErrorLevel := ErrorLevel
  643. DllCall("Ws2_32\FreeAddrInfo", "Ptr", aiResult)
  644. DllCall("Ws2_32\closesocket", "Ptr", sktConnect)
  645. bProcessing := False
  646. ErrorLevel := sErrorLevel
  647. If (sFunction = iMessage) { ;Check if we were called asynchronously
  648. AHKsock_RaiseError(4) ;The WSAAsyncSelect() call failed. The error is in ErrorLevel.
  649.  
  650. ;Call the function to signal that connection failed
  651. If IsFunc(sCurFunction)
  652. %sCurFunction%("CONNECTED", -1)
  653. }
  654. Return 7 ;The WSAAsyncSelect() call failed. The error is in ErrorLevel.
  655. }
  656.  
  657. ;Connect to server (the connect() call also implicitly binds the socket to any host address and any port)
  658. iResult := DllCall("Ws2_32\connect", "Ptr", sktConnect, "Ptr", NumGet(iPointer+0, 16 + 2 * A_PtrSize), "Int", NumGet(iPointer+0, 16))
  659. If ErrorLevel Or ((iResult = -1) And (AHKsock_LastError() != 10035)) { ;Check for any error other than WSAEWOULDBLOCK
  660. sErrorLevel := ErrorLevel ? ErrorLevel : AHKsock_LastError()
  661. DllCall("Ws2_32\FreeAddrInfo", "Ptr", aiResult)
  662. DllCall("Ws2_32\closesocket", "Ptr", sktConnect)
  663. bProcessing := False
  664. ErrorLevel := sErrorLevel
  665. If (sFunction = iMessage) { ;Check if we were called asynchronously
  666. AHKsock_RaiseError(5) ;The connect() call failed. The error is in ErrorLevel.
  667.  
  668. ;Call the function to signal that connection failed
  669. If IsFunc(sCurFunction)
  670. %sCurFunction%("CONNECTED", -1)
  671. }
  672. Return 8 ;The connect() call failed. The error is in ErrorLevel.
  673. }
  674. }
  675.  
  676. AHKsock_Send(iSocket, ptrData = 0, iLength = 0) {
  677.  
  678. ;Make sure the socket is on record. Fail-safe
  679. If Not AHKsock_Sockets("Index", iSocket)
  680. Return -4 ;The socket specified in iSocket is not a recognized socket.
  681.  
  682. ;Make sure Winsock has been started up
  683. If Not AHKsock_Startup(1)
  684. Return -1 ;WSAStartup hasn't been called yet.
  685.  
  686. ;Make sure the socket is cleared for sending
  687. If Not AHKsock_Sockets("GetSend", iSocket)
  688. Return -5 ;The socket specified in iSocket is not cleared for sending.
  689.  
  690. /*! Uncomment this block to simulate the possibility of an incomplete send()
  691. Random, iRand, 1, 100
  692. If (iRand <= 30) { ;Probability of failure of 30%
  693. Random, iRand, 1, iLength - 1 ;Randomize how much of the data will not be sent
  694. iLength -= iRand
  695. }
  696. */
  697.  
  698. iSendResult := DllCall("Ws2_32\send", "Ptr", iSocket, "Ptr", ptrData, "Int", iLength, "Int", 0)
  699. If (iSendResult = -1) And ((iErr := AHKsock_LastError()) = 10035) { ;Check specifically for WSAEWOULDBLOCK
  700. AHKsock_Sockets("SetSend", iSocket, False) ;Update socket's send status
  701. Return -2 ;Calling send() would have blocked the thread. Try again once you get the proper update.
  702. } Else If (iSendResult = -1) Or ErrorLevel {
  703. ErrorLevel := ErrorLevel ? ErrorLevel : iErr
  704. Return -3 ;The send() call failed. The error is in ErrorLevel.
  705. } Else Return iSendResult ;The send() operation was successful
  706. }
  707.  
  708. AHKsock_ForceSend(iSocket, ptrData, iLength) {
  709.  
  710. ;Make sure Winsock has been started up
  711. If Not AHKsock_Startup(1)
  712. Return -1 ;WSAStartup hasn't been called yet
  713.  
  714. ;Make sure the socket is on record. Fail-safe
  715. If Not AHKsock_Sockets("Index", iSocket)
  716. Return -4
  717.  
  718. ;Make sure that we're not in Critical, or we won't be able to wait for FD_WRITE messages
  719. If A_IsCritical
  720. Return -5
  721.  
  722. ;Extra precaution to make sure FD_WRITE messages can make it
  723. Thread, Priority, 0
  724.  
  725. ;We need to make sure not to fill up the send buffer in one call, or we'll get a performance hit.
  726. ;http://support.microsoft.com/kb/823764
  727.  
  728. ;Get the socket's send buffer size
  729. If ((iMaxChunk := AHKsock_SockOpt(iSocket, "SO_SNDBUF")) = -1)
  730. Return -6
  731.  
  732. ;Check if we'll be sending in chunks or not
  733. If (iMaxChunk <= 1) {
  734.  
  735. ;We'll be sending as much as possible everytime!
  736.  
  737. Loop { ;Keep sending the data until we're done or until an error occurs
  738.  
  739. ;Wait until we can send data (ie. when FD_WRITE arrives)
  740. While Not AHKsock_Sockets("GetSend", iSocket)
  741. Sleep -1
  742.  
  743. Loop { ;Keep sending the data until we get WSAEWOULDBLOCK or until an error occurs
  744. If ((iSendResult := AHKsock_Send(iSocket, ptrData, iLength)) < 0) {
  745. If (iSendResult = -2) ;Check specifically for WSAEWOULDBLOCK
  746. Break ;Calling send() would have blocked the thread. Break the loop and we'll try again after we
  747. ;receive FD_WRITE
  748. Else Return iSendResult ;Something bad happened with AHKsock_Send. Return the same value we got.
  749. } Else {
  750.  
  751. ;AHKsock_Send was able to send bytes. Let's check if it sent only part of what we requested
  752. If (iSendResult < iLength) ;Move the offset up by what we were able to send
  753. ptrData += iSendResult, iLength -= iSendResult
  754. Else Return ;We're done sending all the data
  755. }
  756. }
  757. }
  758. } Else {
  759.  
  760. ;We'll be sending in chunks of just under the send buffer size to avoid the performance hit
  761.  
  762. iMaxChunk -= 1 ;Reduce by 1 to be smaller than the send buffer
  763. Loop { ;Keep sending the data until we're done or until an error occurs
  764.  
  765. ;Wait until we can send data (ie. when FD_WRITE arrives)
  766. While Not AHKsock_Sockets("GetSend", iSocket)
  767. Sleep -1
  768.  
  769. ;Check if we have less than the max chunk to send
  770. If (iLength < iMaxChunk) {
  771.  
  772. Loop { ;Keep sending the data until we get WSAEWOULDBLOCK or until an error occurs
  773. ;Send using the traditional offset method
  774. If ((iSendResult := AHKsock_Send(iSocket, ptrData, iLength)) < 0) {
  775. If (iSendResult = -2) ;Check specifically for WSAEWOULDBLOCK
  776. Break ;Calling send() would have blocked the thread. Break the loop and we'll try again after we
  777. ;receive FD_WRITE
  778. Else Return iSendResult ;Something bad happened with AHKsock_Send. Return the same value we got.
  779. } Else {
  780.  
  781. ;AHKsock_Send was able to send bytes. Let's check if it sent only part of what we requested
  782. If (iSendResult < iLength) ;Move the offset up by what we were able to send
  783. ptrData += iSendResult, iLength -= iSendResult
  784. Else Return ;We're done sending all the data
  785. }
  786. }
  787. } Else {
  788.  
  789. ;Send up to max chunk
  790. If ((iSendResult := AHKsock_Send(iSocket, ptrData, iMaxChunk)) < 0) {
  791. If (iSendResult = -2) ;Check specifically for WSAEWOULDBLOCK
  792. Continue ;Calling send() would have blocked the thread. Continue the loop and we'll try again after
  793. ;we receive FD_WRITE
  794. Else Return iSendResult ;Something bad happened with AHKsock_Send. Return the same value we got.
  795. } Else ptrData += iSendResult, iLength -= iSendResult ;Move up offset by updating the pointer and length
  796. }
  797. }
  798. }
  799. }
  800.  
  801. AHKsock_Close(iSocket = -1, iTimeout = 5000) {
  802.  
  803. ;Make sure Winsock has been started up
  804. If Not AHKsock_Startup(1)
  805. Return ;There's nothing to close
  806.  
  807. If (iSocket = -1) { ;We need to close all the sockets
  808.  
  809. ;Check if we even have sockets to close
  810. If Not AHKsock_Sockets() {
  811. DllCall("Ws2_32\WSACleanup")
  812. AHKsock_Startup(2) ;Reset the value to show that we've turned off Winsock
  813. Return ;We're done!
  814. }
  815.  
  816. ;Take the current time (needed for time-outing)
  817. iStartClose := A_TickCount
  818.  
  819. Loop % AHKsock_Sockets() ;Close all sockets and cleanup
  820. AHKsock_ShutdownSocket(AHKsock_Sockets("GetSocketFromIndex", A_Index))
  821.  
  822. ;Check if we're in the OnExit subroutine
  823. If Not A_ExitReason {
  824.  
  825. A_IsCriticalOld := A_IsCritical
  826.  
  827. ;Make sure we can still receive FD_CLOSE msgs
  828. Critical, Off
  829. Thread, Priority, 0
  830.  
  831. ;We can try a graceful shutdown or wait for a timeout
  832. While (AHKsock_Sockets()) And (A_TickCount - iStartClose < iTimeout)
  833. Sleep, -1
  834.  
  835. ;Restore previous Critical
  836. Critical, %A_IsCriticalOld%
  837. }
  838.  
  839. /*! Used for debugging purposes only
  840. If (i := AHKsock_Sockets()) {
  841. If (i = 1)
  842. OutputDebug, % "Cleaning up now, with the socket " AHKsock_Sockets("GetSocketFromIndex", 1) " remaining..."
  843. Else {
  844. OutputDebug, % "Cleaning up now, with the following sockets remaining:"
  845. Loop % AHKsock_Sockets() {
  846. OutputDebug, % AHKsock_Sockets("GetSocketFromIndex", A_Index)
  847. }
  848. }
  849. }
  850. */
  851.  
  852. DllCall("Ws2_32\WSACleanup")
  853. AHKsock_Startup(2) ;Reset the value to show that we've turned off Winsock
  854.  
  855. ;Close only one socket
  856. } Else If AHKsock_ShutdownSocket(iSocket) ;Error-checking
  857. Return 1 ;The shutdown() call failed. The error is in ErrorLevel.
  858. }
  859.  
  860. AHKsock_GetAddrInfo(sHostName, ByRef sIPList, bOne = False) {
  861.  
  862. ;Make sure Winsock has been started up
  863. If (i := AHKsock_Startup())
  864. Return i ;Return the same error (error 1 and 2)
  865.  
  866. ;Resolve the address and port
  867. VarSetCapacity(aiHints, 16 + 4 * A_PtrSize, 0)
  868. NumPut(2, aiHints, 4, "Int") ;ai_family = AF_INET
  869. NumPut(1, aiHints, 8, "Int") ;ai_socktype = SOCK_STREAM
  870. NumPut(6, aiHints, 12, "Int") ;ai_protocol = IPPROTO_TCP
  871. iResult := DllCall("Ws2_32\GetAddrInfo", "Ptr", &sHostName, "Ptr", 0, "Ptr", &aiHints, "Ptr*", aiResult)
  872. If (iResult = 11001) ;Check specifically for WSAHOST_NOT_FOUND since it's the most common error
  873. Return 3 ;Received WSAHOST_NOT_FOUND. No such host is known.
  874. Else If (iResult != 0) Or ErrorLevel { ;Check for any other error
  875. ErrorLevel := ErrorLevel ? ErrorLevel : iResult
  876. Return 4 ;The getaddrinfo() call failed. The error is in ErrorLevel.
  877. }
  878.  
  879. If bOne
  880. sIPList := DllCall("Ws2_32\inet_ntoa", "UInt", NumGet(NumGet(aiResult+0, 16 + 2 * A_PtrSize)+4, 0, "UInt"), "AStr")
  881. Else {
  882.  
  883. ;Start with the first addrinfo struct
  884. iPointer := aiResult, sIPList := ""
  885. While iPointer {
  886. s := DllCall("Ws2_32\inet_ntoa", "UInt", NumGet(NumGet(iPointer+0, 16 + 2 * A_PtrSize)+4, 0, "UInt"), "AStr")
  887. iPointer := NumGet(iPointer+0, 16 + 3 * A_PtrSize) ;Go to the next addrinfo struct
  888. sIPList .= s (iPointer ? "`n" : "") ;Add newline only if it's not the last one
  889. }
  890. }
  891.  
  892. ;We're done
  893. DllCall("Ws2_32\FreeAddrInfo", "Ptr", aiResult)
  894. }
  895.  
  896. AHKsock_GetNameInfo(sIP, ByRef sHostName, sPort = 0, ByRef sService = "") {
  897.  
  898. ;Make sure Winsock has been started up
  899. If (i := AHKsock_Startup())
  900. Return i ;Return the same error (error 1 and 2)
  901.  
  902. ;Translate to IN_ADDR
  903. iIP := DllCall("Ws2_32\inet_addr", "AStr", sIP, "UInt")
  904. If (iIP = 0 Or iIP = 0xFFFFFFFF) ;Check for INADDR_NONE or INADDR_ANY
  905. Return 3 ;The IP address supplied in sIP is invalid.
  906.  
  907. ;Construct a sockaddr struct
  908. VarSetCapacity(tSockAddr, 16, 0)
  909. NumPut(2, tSockAddr, 0, "Short") ;ai_family = AF_INET
  910. NumPut(iIP, tSockAddr, 4, "UInt") ;Put in the IN_ADDR
  911.  
  912. ;Fill in the port field if we're also looking up the service name
  913. If sPort ;Translate to network byte order
  914. NumPut(DllCall("Ws2_32\htons", "UShort", sPort, "UShort"), tSockAddr, 2, "UShort")
  915.  
  916. ;Prep vars
  917. VarSetCapacity(sHostName, 1025 * 2, 0) ;NI_MAXHOST
  918. If sPort
  919. VarSetCapacity(sService, 32 * 2, 0) ;NI_MAXSERV
  920.  
  921. iResult := DllCall("Ws2_32\GetNameInfoW", "Ptr", &tSockAddr, "Int", 16, "Str", sHostName, "UInt", 1025 * 2
  922. , sPort ? "Str" : "UInt", sPort ? sService : 0, "UInt", 32 * 2, "Int", 0)
  923. If (iResult != 0) Or ErrorLevel {
  924. ErrorLevel := ErrorLevel ? ErrorLevel : DllCall("Ws2_32\WSAGetLastError")
  925. Return 4 ;The getnameinfo() call failed. The error is in ErrorLevel.
  926. }
  927. }
  928.  
  929. AHKsock_SockOpt(iSocket, sOption, iValue = -1) {
  930.  
  931. ;Prep variable
  932. VarSetCapacity(iOptVal, iOptValLength := 4, 0)
  933. If (iValue <> -1)
  934. NumPut(iValue, iOptVal, 0, "UInt")
  935.  
  936. If (sOption = "SO_KEEPALIVE") {
  937. intLevel := 0xFFFF ;SOL_SOCKET
  938. intOptName := 0x0008 ;SO_KEEPALIVE
  939. } Else If (sOption = "SO_SNDBUF") {
  940. intLevel := 0xFFFF ;SOL_SOCKET
  941. intOptName := 0x1001 ;SO_SNDBUF
  942. } Else If (sOption = "SO_RCVBUF") {
  943. intLevel := 0xFFFF ;SOL_SOCKET
  944. intOptName := 0x1002 ;SO_SNDBUF
  945. } Else If (sOption = "TCP_NODELAY") {
  946. intLevel := 6 ;IPPROTO_TCP
  947. intOptName := 0x0001 ;TCP_NODELAY
  948. }
  949.  
  950. ;Check if we're getting or setting
  951. If (iValue = -1) {
  952. iResult := DllCall("Ws2_32\getsockopt", "Ptr", iSocket, "Int", intLevel, "Int", intOptName
  953. , "UInt*", iOptVal, "Int*", iOptValLength)
  954. If (iResult = -1) Or ErrorLevel { ;Check for SOCKET_ERROR
  955. ErrorLevel := ErrorLevel ? ErrorLevel : AHKsock_LastError()
  956. Return -1
  957. } Else Return iOptVal
  958. } Else {
  959. iResult := DllCall("Ws2_32\setsockopt", "Ptr", iSocket, "Int", intLevel, "Int", intOptName
  960. , "Ptr", &iOptVal, "Int", iOptValLength)
  961. If (iResult = -1) Or ErrorLevel { ;Check for SOCKET_ERROR
  962. ErrorLevel := ErrorLevel ? ErrorLevel : AHKsock_LastError()
  963. Return -2
  964. }
  965. }
  966. }
  967.  
  968. /*******************\
  969. Support functions |
  970. */
  971.  
  972. AHKsock_Startup(iMode = 0) {
  973. Static bAlreadyStarted
  974.  
  975. /*
  976. iMode = 0 ;Turns on WSAStartup()
  977. iMode = 1 ;Returns whether or not WSAStartup has been called
  978. iMode = 2 ;Resets the static variable to force another call next time iMode = 0
  979. */
  980.  
  981. If (iMode = 2)
  982. bAlreadyStarted := False
  983. Else If (iMode = 1)
  984. Return bAlreadyStarted
  985. Else If Not bAlreadyStarted { ;iMode = 0. Call the function only if it hasn't already been called.
  986.  
  987. ;Start it up - request version 2.2
  988. VarSetCapacity(wsaData, A_PtrSize = 4 ? 400 : 408, 0)
  989. iResult := DllCall("Ws2_32\WSAStartup", "UShort", 0x0202, "Ptr", &wsaData)
  990. If (iResult != 0) Or ErrorLevel {
  991. ErrorLevel := ErrorLevel ? ErrorLevel : iResult
  992. Return 1
  993. }
  994.  
  995. ;Make sure the Winsock DLL supports at least version 2.2
  996. If (NumGet(wsaData, 2, "UShort") < 0x0202) {
  997. DllCall("Ws2_32\WSACleanup") ;Abort
  998. ErrorLevel := "The Winsock DLL does not support version 2.2."
  999. Return 2
  1000. }
  1001.  
  1002. bAlreadyStarted := True
  1003. }
  1004. }
  1005.  
  1006. AHKsock_ShutdownSocket(iSocket) {
  1007.  
  1008. ;Check if it's a listening socket
  1009. sName := AHKsock_Sockets("GetName", iSocket)
  1010. If (sName != A_Space) { ;It's not a listening socket. Shutdown send operations.
  1011. iResult := DllCall("Ws2_32\shutdown", "Ptr", iSocket, "Int", 1) ;SD_SEND
  1012. If (iResult = -1) Or ErrorLevel {
  1013. sErrorLevel := ErrorLevel ? ErrorLevel : AHKsock_LastError()
  1014. DllCall("Ws2_32\closesocket", "Ptr", iSocket)
  1015. AHKsock_Sockets("Delete", iSocket)
  1016. ErrorLevel := sErrorLevel
  1017. Return 1
  1018. }
  1019.  
  1020. ;Mark it
  1021. AHKsock_Sockets("SetShutdown", iSocket)
  1022.  
  1023. } Else {
  1024. DllCall("Ws2_32\closesocket", "Ptr", iSocket) ;It's only a listening socket
  1025. AHKsock_Sockets("Delete", iSocket) ;Remove it from the array
  1026. }
  1027. }
  1028.  
  1029. /***********************\
  1030. AsyncSelect functions |
  1031. */
  1032. ;FD_READ | FD_WRITE | FD_ACCEPT | FD_CLOSE
  1033. AHKsock_RegisterAsyncSelect(iSocket, fFlags = 43, sFunction = "AHKsock_AsyncSelect", iMsg = 0) {
  1034. Static hwnd := False
  1035.  
  1036. If Not hwnd { ;Use the main AHK window
  1037. A_DetectHiddenWindowsOld := A_DetectHiddenWindows
  1038. DetectHiddenWindows, On
  1039. WinGet, hwnd, ID, % "ahk_pid " DllCall("GetCurrentProcessId") " ahk_class AutoHotkey"
  1040. DetectHiddenWindows, %A_DetectHiddenWindowsOld%
  1041. }
  1042.  
  1043. iMsg := iMsg ? iMsg : AHKsock_Settings("Message")
  1044. If (OnMessage(iMsg) <> sFunction)
  1045. OnMessage(iMsg, sFunction)
  1046.  
  1047. iResult := DllCall("Ws2_32\WSAAsyncSelect", "Ptr", iSocket, "Ptr", hwnd, "UInt", iMsg, "Int", fFlags)
  1048. If (iResult = -1) Or ErrorLevel { ;Check for SOCKET_ERROR
  1049. ErrorLevel := ErrorLevel ? ErrorLevel : AHKsock_LastError()
  1050. Return 1
  1051. }
  1052. }
  1053.  
  1054. AHKsock_AsyncSelect(wParam, lParam) {
  1055. Critical ;So that messages are buffered
  1056.  
  1057. ;wParam parameter identifies the socket on which a network event has occurred
  1058. ;The low word of lParam specifies the network event that has occurred.
  1059. ;The high word of lParam contains any error code
  1060.  
  1061. ;Make sure the socket is on record. Fail-safe
  1062. If Not AHKsock_Sockets("Index", wParam)
  1063. Return
  1064.  
  1065. iEvent := lParam & 0xFFFF, iErrorCode := lParam >> 16
  1066.  
  1067. /*! Used for debugging purposes
  1068. OutputDebug, % "AsyncSelect - A network event " iEvent " has occurred on socket " wParam
  1069. If iErrorCode
  1070. OutputDebug, % "AsyncSelect - Error code = " iErrorCode
  1071. */
  1072.  
  1073. If (iEvent = 1) { ;FD_READ
  1074.  
  1075. ;Check for error
  1076. If iErrorCode { ;WSAENETDOWN is the only possible
  1077. ErrorLevel := iErrorCode
  1078. ;FD_READ event received with an error. The error is in ErrorLevel. The socket is in iSocket.
  1079. AHKsock_RaiseError(6, wParam)
  1080. Return
  1081. }
  1082.  
  1083. VarSetCapacity(bufReceived, bufReceivedLength := AHKsock_Settings("Buffer"), 0)
  1084. iResult := DllCall("Ws2_32\recv", "UInt", wParam, "Ptr", &bufReceived, "Int", bufReceivedLength, "Int", 0)
  1085. If (iResult > 0) { ;We received data!
  1086. VarSetCapacity(bufReceived, -1) ;Update the internal length
  1087.  
  1088. ;Get associated function and call it
  1089. If IsFunc(sFunc := AHKsock_Sockets("GetFunction", wParam))
  1090. %sFunc%("RECEIVED", wParam, AHKsock_Sockets("GetName", wParam)
  1091. , AHKsock_Sockets("GetAddr", wParam)
  1092. , AHKsock_Sockets("GetPort", wParam), bufReceived, iResult)
  1093.  
  1094. ;Check for error other than WSAEWOULDBLOCK
  1095. } Else If ErrorLevel Or ((iResult = -1) And Not ((iErrorCode := AHKsock_LastError()) = 10035)) {
  1096. ErrorLevel := ErrorLevel ? ErrorLevel : iErrorCode
  1097. AHKsock_RaiseError(7, wParam) ;The recv() call failed. The error is in ErrorLevel. The socket is in iSocket.
  1098. iResult = -1 ;So that if it's a spoofed call from FD_CLOSE, we exit the loop and close the socket
  1099. }
  1100.  
  1101. ;Here, we bother with returning a value in case it's a spoofed call from FD_CLOSE
  1102. Return iResult
  1103.  
  1104. } Else If (iEvent = 2) { ;FD_WRITE
  1105.  
  1106. ;Check for error
  1107. If iErrorCode { ;WSAENETDOWN is the only possible
  1108. ErrorLevel := iErrorCode
  1109. ;FD_WRITE event received with an error. The error is in ErrorLevel. The socket is in iSocket.
  1110. AHKsock_RaiseError(8, wParam)
  1111. Return
  1112. }
  1113.  
  1114. ;Update socket's setting
  1115. AHKsock_Sockets("SetSend", wParam, True)
  1116.  
  1117. ;Make sure the socket isn't already shut down
  1118. If Not AHKsock_Sockets("GetShutdown", wParam)
  1119. If IsFunc(sFunc := AHKsock_Sockets("GetFunction", wParam))
  1120. %sFunc%("SEND", wParam, AHKsock_Sockets("GetName", wParam)
  1121. , AHKsock_Sockets("GetAddr", wParam)
  1122. , AHKsock_Sockets("GetPort", wParam))
  1123.  
  1124. } Else If (iEvent = 8) { ;FD_ACCEPT
  1125.  
  1126. ;Check for error
  1127. If iErrorCode { ;WSAENETDOWN is the only possible
  1128. ErrorLevel := iErrorCode
  1129. ;FD_ACCEPT event received with an error. The error is in ErrorLevel. The socket is in iSocket.
  1130. AHKsock_RaiseError(9, wParam)
  1131. Return
  1132. }
  1133.  
  1134. ;We need to accept the connection
  1135. VarSetCapacity(tSockAddr, tSockAddrLength := 16, 0)
  1136. sktClient := DllCall("Ws2_32\accept", "Ptr", wParam, "Ptr", &tSockAddr, "Int*", tSockAddrLength)
  1137. If (sktClient = -1) And ((iErrorCode := AHKsock_LastError()) = 10035) ;Check specifically for WSAEWOULDBLOCK
  1138. Return ;We'll be called again next time we can retry accept()
  1139. Else If (sktClient = -1) Or ErrorLevel { ;Check for INVALID_SOCKET
  1140. ErrorLevel := ErrorLevel ? ErrorLevel : iErrorCode
  1141. ;The accept() call failed. The error is in ErrorLevel. The listening socket is in iSocket.
  1142. AHKsock_RaiseError(10, wParam)
  1143. Return
  1144. }
  1145.  
  1146. ;Add to array
  1147. sName := ""
  1148. sAddr := DllCall("Ws2_32\inet_ntoa", "UInt", NumGet(tSockAddr, 4, "UInt"), "AStr")
  1149. sPort := AHKsock_Sockets("GetPort", wParam)
  1150. sFunc := AHKsock_Sockets("GetFunction", wParam)
  1151. AHKsock_Sockets("Add", sktClient, sName, sAddr, sPort, sFunc)
  1152.  
  1153. ;Go back to listening
  1154. iResult := DllCall("Ws2_32\listen", "Ptr", wParam, "Int", 0x7FFFFFFF) ;SOMAXCONN
  1155. If (iResult = -1) Or ErrorLevel { ;Check for SOCKET_ERROR
  1156. sErrorLevel := ErrorLevel ? ErrorLevel : AHKsock_LastError()
  1157. DllCall("Ws2_32\closesocket", "Ptr", wParam)
  1158. AHKsock_Sockets("Delete", wParam) ;Remove from array
  1159. ErrorLevel := sErrorLevel
  1160. ;The listen() call failed. The error is in ErrorLevel. The listening socket is in iSocket.
  1161. AHKsock_RaiseError(12, wParam)
  1162. Return
  1163. }
  1164.  
  1165. ;Get associated function and call it
  1166. If IsFunc(sFunc)
  1167. %sFunc%("ACCEPTED", sktClient, sName, sAddr, sPort)
  1168.  
  1169. } Else If (iEvent = 32) { ;FD_CLOSE
  1170.  
  1171. ;Keep receiving data before closing the socket by spoofing an FD_READ event to call recv()
  1172. While (AHKsock_AsyncSelect(wParam, 1) > 0)
  1173. Sleep, -1
  1174.  
  1175. ;Check if we initiated it
  1176. If Not AHKsock_Sockets("GetShutdown", wParam) {
  1177.  
  1178. ;Last chance to send data. Get associated function and call it.
  1179. If IsFunc(sFunc := AHKsock_Sockets("GetFunction", wParam))
  1180. %sFunc%("SENDLAST", wParam, AHKsock_Sockets("GetName", wParam)
  1181. , AHKsock_Sockets("GetAddr", wParam)
  1182. , AHKsock_Sockets("GetPort", wParam))
  1183.  
  1184. ;Shutdown the socket. This is to attempt a graceful shutdown
  1185. If AHKsock_ShutdownSocket(wParam) {
  1186. ;The shutdown() call failed. The error is in ErrorLevel. The socket is in iSocket.
  1187. AHKsock_RaiseError(13, wParam)
  1188. Return
  1189. }
  1190. }
  1191.  
  1192. ;We just have to close the socket then
  1193. DllCall("Ws2_32\closesocket", "Ptr", wParam)
  1194.  
  1195. ;Get associated data before deleting
  1196. sFunc := AHKsock_Sockets("GetFunction", wParam)
  1197. sName := AHKsock_Sockets("GetName", wParam)
  1198. sAddr := AHKsock_Sockets("GetAddr", wParam)
  1199. sPort := AHKsock_Sockets("GetPort", wParam)
  1200.  
  1201. ;We can remove it from the array
  1202. AHKsock_Sockets("Delete", wParam)
  1203.  
  1204. If IsFunc(sFunc)
  1205. %sFunc%("DISCONNECTED", wParam, sName, sAddr, sPort)
  1206. }
  1207. }
  1208.  
  1209. /******************\
  1210. Array controller |
  1211. */
  1212.  
  1213. AHKsock_Sockets(sAction = "Count", iSocket = "", sName = "", sAddr = "", sPort = "", sFunction = "") {
  1214. Static
  1215. Static aSockets0 := 0
  1216. Static iLastSocket := 0xFFFFFFFF ;Cache to lessen index lookups on the same socket
  1217. Local i, ret, A_IsCriticalOld
  1218.  
  1219. A_IsCriticalOld := A_IsCritical
  1220. Critical
  1221.  
  1222. If (sAction = "Count") {
  1223. ret := aSockets0
  1224.  
  1225. } Else If (sAction = "Add") {
  1226. aSockets0 += 1 ;Expand array
  1227. aSockets%aSockets0%_Sock := iSocket
  1228. aSockets%aSockets0%_Name := sName
  1229. aSockets%aSockets0%_Addr := sAddr
  1230. aSockets%aSockets0%_Port := sPort
  1231. aSockets%aSockets0%_Func := sFunction
  1232. aSockets%aSockets0%_Shutdown := False
  1233. aSockets%aSockets0%_Send := False
  1234.  
  1235. } Else If (sAction = "Delete") {
  1236.  
  1237. ;First we need the index
  1238. i := (iSocket = iLastSocket) ;Check cache
  1239. ? iLastSocketIndex
  1240. : AHKsock_Sockets("Index", iSocket)
  1241.  
  1242. If i {
  1243. iLastSocket := 0xFFFF ;Clear cache
  1244. If (i < aSockets0) { ;Let the last item overwrite this one
  1245. aSockets%i%_Sock := aSockets%aSockets0%_Sock
  1246. aSockets%i%_Name := aSockets%aSockets0%_Name
  1247. aSockets%i%_Addr := aSockets%aSockets0%_Addr
  1248. aSockets%i%_Port := aSockets%aSockets0%_Port
  1249. aSockets%i%_Func := aSockets%aSockets0%_Func
  1250. aSockets%i%_Shutdown := aSockets%aSockets0%_Shutdown
  1251. aSockets%i%_Send := aSockets%aSockets0%_Send
  1252.  
  1253. }
  1254. aSockets0 -= 1 ;Remove element
  1255. }
  1256.  
  1257. } Else If (sAction = "GetName") {
  1258. i := (iSocket = iLastSocket) ;Check cache
  1259. ? iLastSocketIndex
  1260. : AHKsock_Sockets("Index", iSocket)
  1261. ret := aSockets%i%_Name
  1262.  
  1263. } Else If (sAction = "GetAddr") {
  1264. i := (iSocket = iLastSocket) ;Check cache
  1265. ? iLastSocketIndex
  1266. : AHKsock_Sockets("Index", iSocket)
  1267. ret := aSockets%i%_Addr
  1268.  
  1269. } Else If (sAction = "GetPort") {
  1270. i := (iSocket = iLastSocket) ;Check cache
  1271. ? iLastSocketIndex
  1272. : AHKsock_Sockets("Index", iSocket)
  1273. ret := aSockets%i%_Port
  1274.  
  1275. } Else If (sAction = "GetFunction") {
  1276. i := (iSocket = iLastSocket) ;Check cache
  1277. ? iLastSocketIndex
  1278. : AHKsock_Sockets("Index", iSocket)
  1279. ret := aSockets%i%_Func
  1280.  
  1281. } Else If (sAction = "SetFunction") {
  1282. i := (iSocket = iLastSocket) ;Check cache
  1283. ? iLastSocketIndex
  1284. : AHKsock_Sockets("Index", iSocket)
  1285. aSockets%i%_Func := sName
  1286.  
  1287. } Else If (sAction = "GetSend") {
  1288. i := (iSocket = iLastSocket) ;Check cache
  1289. ? iLastSocketIndex
  1290. : AHKsock_Sockets("Index", iSocket)
  1291. ret := aSockets%i%_Send
  1292.  
  1293. } Else If (sAction = "SetSend") {
  1294. i := (iSocket = iLastSocket) ;Check cache
  1295. ? iLastSocketIndex
  1296. : AHKsock_Sockets("Index", iSocket)
  1297. aSockets%i%_Send := sName
  1298.  
  1299. } Else If (sAction = "GetShutdown") {
  1300. i := (iSocket = iLastSocket) ;Check cache
  1301. ? iLastSocketIndex
  1302. : AHKsock_Sockets("Index", iSocket)
  1303. ret := aSockets%i%_Shutdown
  1304.  
  1305. } Else If (sAction = "SetShutdown") {
  1306. i := (iSocket = iLastSocket) ;Check cache
  1307. ? iLastSocketIndex
  1308. : AHKsock_Sockets("Index", iSocket)
  1309. aSockets%i%_Shutdown := True
  1310.  
  1311. } Else If (sAction = "GetSocketFromNamePort") {
  1312. Loop % aSockets0 {
  1313. If (aSockets%A_Index%_Name = iSocket)
  1314. And (aSockets%A_Index%_Port = sName) {
  1315. ret := aSockets%A_Index%_Sock
  1316. Break
  1317. }
  1318. }
  1319.  
  1320. } Else If (sAction = "GetSocketFromIndex") {
  1321. ret := aSockets%iSocket%_Sock
  1322.  
  1323. } Else If (sAction = "Index") {
  1324. Loop % aSockets0 {
  1325. If (aSockets%A_Index%_Sock = iSocket) {
  1326. iLastSocketIndex := A_Index, iLastSocket := iSocket
  1327. ret := A_Index
  1328. Break
  1329. }
  1330. }
  1331. }
  1332.  
  1333. ;Restore old Critical setting
  1334. Critical %A_IsCriticalOld%
  1335. Return ret
  1336. }
  1337.  
  1338. /*****************\
  1339. Error Functions |
  1340. */
  1341.  
  1342. AHKsock_LastError() {
  1343. Return DllCall("Ws2_32\WSAGetLastError")
  1344. }
  1345.  
  1346. AHKsock_ErrorHandler(sFunction = """") {
  1347. Static sCurrentFunction
  1348. If (sFunction = """")
  1349. Return sCurrentFunction
  1350. Else sCurrentFunction := sFunction
  1351. }
  1352.  
  1353. AHKsock_RaiseError(iError, iSocket = -1) {
  1354. If IsFunc(sFunc := AHKsock_ErrorHandler())
  1355. %sFunc%(iError, iSocket)
  1356. }
  1357.  
  1358. /*******************\
  1359. Settings Function |
  1360. */
  1361.  
  1362. AHKsock_Settings(sSetting, sValue = "") {
  1363. Static iMessage := 0x8000
  1364. Static iBuffer := 65536
  1365.  
  1366. If (sSetting = "Message") {
  1367. If Not sValue
  1368. Return iMessage
  1369. Else iMessage := (sValue = "Reset") ? 0x8000 : sValue
  1370. } Else If (sSetting = "Buffer") {
  1371. If Not sValue
  1372. Return iBuffer
  1373. Else iBuffer := (sValue = "Reset") ? 65536 : sValue
  1374. }
  1375. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement