Jump to content

Sky Slate Blueberry Blackcurrant Watermelon Strawberry Orange Banana Apple Emerald Chocolate
Photo

AHKsock - A simple AHK implementation of Winsock (TCP/IP)


  • Please log in to reply
179 replies to this topic
Zaelia
  • Members
  • 754 posts
  • Last active: Jan 17 2015 02:38 AM
  • Joined: 31 Oct 2008
You have to close your Client socket, and also close the Server socket corresponding to this Client, else WinSock will try to connect to a thing already halfy connected. However I dunno how to do it with this library, it was just the idea, good luck !
"You annoy me, therefore I exist."

NeedAhkSockAnsi
  • Guests
  • Last active:
  • Joined: --

It appears Google has cached the Unicode x86/x64 version of this script, but not the ANSI one.


Does anyone have the ansi verison?

DataLife
  • Members
  • 1022 posts
  • Last active: Nov 27 2015 01:09 AM
  • Joined: 27 Apr 2008

It appears Google has cached the Unicode x86/x64 version of this script, but not the ANSI one.


Does anyone have the ansi verison?

Is this the ahksock.ahk that you are needing? Looks like the documentation is included with the script. I would just post the code here but there is a new 60000 character limit on posts.

https://ahknet.autoh...che/AHKsock.ahk
Check out my scripts.  (MyIpChanger) (XPSnap) (SavePictureAs) All my scripts are tested on Windows 7, AutoHotkey 32 bit Ansi unless otherwise stated.

  • Guests
  • Last active:
  • Joined: --
Hi
as the original links are broken anyone have the example codes?
i would like the Example 3 - Chatting for unicode
Thanks

LARK2355
  • Members
  • 9 posts
  • Last active: Sep 28 2013 06:59 AM
  • Joined: 02 Feb 2012
here is my version you can use it to chat or as a layer for a game (original code came from crossfire's example earlier)
server
#Include %A_ScriptDir%\AHKsock.ahk
#SingleInstance IGNORE
; you can change above but you can only have one server for each port so unless you are running multiple servers it will stop a reload without close 
OnExit, CloseAHKsock
Menu, Tray, Icon ,  ahktcp.ico, 1, 1 
sPort =%1%
if (sPort="")
	{
	; you did not send a server Port so i assume you are testing so i will use 27015 for port address
	InputBox, sPort, SERVER PORT, Enter server PORT`n(27015 default), , 170, 200, , , , , 27015
	if ErrorLevel
		ExitApp
	}
loop 512
{
sockets_in_use .=0
}
Gui, Add, ListView, r10 w700 , received|from| on socket
Gui, Add, Text,, Message:
Gui, Add, Edit, vSendthis w300 r1  x+1
Gui, Add, Button, x+1 gGuiBroadcast, Broadcast
Gui, Add, Button, x+1 gGuiSend, or Send to socket
Gui, Add, Edit, vSendsocket w50 r1  x+1
Gui, Add, Button, x+1 gLog, Log
Gui, Add, Button, x+1 gWhoIs, WhoIs
Gui, Show
AHKsock_ErrorHandler("AHKsockErrors")
msg0=hi ,this is the welcome message `n
msg1=message 1`n
msg2=see it works`n
If (i := AHKsock_Listen(sPort, "Server"))
	{
	If (i = 2)
		{
  		;     2: sFunction is not a valid function.
		msgbox Error:- %i% sFunction is not a valid function , 
		ExitApp
		}
	If (i = 3)
		{
  		;      3: The WSAStartup() call failed. The error is in ErrorLevel.
		msgbox Error:- %i% The WSAStartup() call failed , error code = %ErrorLevel% 
		ExitApp
		}
	If (i = 4)
		{
  		;         4: The Winsock DLL does not support version 2.2.
		msgbox Error:- %i% The Winsock DLL does not support version 2.2. , error code = %ErrorLevel% 
		ExitApp
		}
	If (i = 5)
		{
  		;             5: The getaddrinfo() call failed. The error is in ErrorLevel.
		msgbox Error:- %i% The getaddrinfo() call failed. , error code = %ErrorLevel% 
		ExitApp
		}
	If (i = 6)
		{
  		;           6: The socket() call failed. The error is in ErrorLevel.
		msgbox Error:- %i%  The socket() call failed. , error code = %ErrorLevel% 
		ExitApp
		}
	If (i = 7)
		{
  		;               7: The bind() call failed. The error is in ErrorLevel.
		msgbox Error:- %i%  TThe bind() call failed , error code = %ErrorLevel% 
		ExitApp
		}
	If (i = 8)
		{
  		;                8:  The WSAAsyncSelect() call failed
		msgbox Error:- %i%  The WSAAsyncSelect() call failed, error code = %ErrorLevel% 
		ExitApp
		}
	If (i = 9)
		{
  		;               9:  The listen() call failed. The error is in ErrorLevel.
		msgbox Error:- %i%  The WSAAsyncSelect() call failed, error code = %ErrorLevel% 
		ExitApp
		}
	If (i < 2 or i >9)
		{
		donelog .="Send failed with return value = " i " and ErrorLevel = " ErrorLevel "`n"
		msgbox unknown Error:- %i%, error code = %ErrorLevel%   on socket  %mySocket% 
		ExitApp
		}                
	}
sleep 10000
; now a broadcast to all conected (1 if connected)
bSendData=test
bSendDataLength := StrLen(bSendData)  * 2
gosub Broadcast
sleep 10000
; now a broadcast to all conected (1 if connected)
bSendData=this
bSendDataLength := StrLen(bSendData) * 2
gosub Broadcast
Return
WhoIs:
summary=currently connected sockets`n
loop 512
	{
	if (SubStr(sockets_in_use,a_index , 1) = 1)
		{
		summary.="socket " a_index 
 		sName := AHKsock_Sockets("GetName", a_index)
		summary.=" Name " sName 
		sAddr := AHKsock_Sockets("GetAddr",  a_index)
		summary.=" Address "sAddr 
		sPort := AHKsock_Sockets("GetPort",  a_index)
		summary.=" Port " sPort "`n"
		}
	}
msgbox %summary%
return
log:
msgbox %donelog%
return
GuiSend:
GuiControlGet, Sendthis
bSendData=%Sendthis%
GuiControlGet, Sendsocket
bSendDataLength := StrLen(bSendData)  * 2
sendmore(Sendsocket , bSendData , bSendDataLength )
return
GuiBroadcast:
GuiControlGet, Sendthis
bSendData=%Sendthis%
bSendDataLength := StrLen(bSendData)  * 2

Broadcast:
loop 512
	{
	if (SubStr(sockets_in_use,a_index , 1) = 1)
		{
		iSocket :=a_index
		donelog .=  "broadcasting to socket" iSocket ":-" bSendData " which has " bSendDataLength "bytes`n"
		sendmore(iSocket , bSendData , bSendDataLength )
		}
	}
; msgbox %sockets_in_use%
Return
GuiClose:
ExitApp
return
CloseAHKsock:
AHKsock_Close() 
; msgbox %donelog%
; msgbox %recvdtext%

ExitApp
sendmore(iSocket = 0, ByRef bSendData = 0, bSendDataLength = 0)
	{
	Global donelog
	bSendDataSent := 0 
	donelog .=  " `[email protected]"
     	Loop
		{
		donelog .="trying to send" bSendData " with " bSendDataLength "bytes, out on socket " iSocket 
		If ((i := AHKsock_Send(iSocket, &bSendData + bSendDataSent, bSendDataLength - bSendDataSent)) < 0)
			{
			If (i = -1)
				{
  				;  -1: WSAStartup hasn't been called yet.
				msgbox Error:- %i% WSAStartup hasn't been called yet , error code = %ErrorLevel%   on socket  %iSocket% 
				break
				}
 			If (i = -2)
				{
				;2: Received WSAEWOULDBLOCK. This means that calling send() would have blocked the thread. we can handle that so add to log
				donelog .="more to send " i 
				}
  			If (i = -3)
				{
				;-3: The send() call failed. The error is in ErrorLevel.
				msgbox Error:- %i% WSAStartup hasn't been called yet , error code = %ErrorLevel%   on socket  %iSocket% 
				break
				}
  			If (i = -4)
				{
				;    -4: The socket specified in iSocket is not a valid socket. This means either that the socket in iSocket hasn't been created using AHKsock_Connect or AHKsock_Listen, or that the socket has already been destroyed.
				msgbox Error:- %i% not a valid socket ,error code = %ErrorLevel%   on socket  %iSocket% 
				break
				}
 			If (i = -5)
				{
				;       -5: The socket specified in iSocket is not cleared for sending. You haven't waited for the SEND event before calling, either ever, or not since you last received WSAEWOULDBLOCK.
				msgbox Error:- %i% Socket is not cleared for sending , error code = %ErrorLevel%   on socket  %iSocket% 
				break
				}
			If (i < -5 or i > -1)
				{
				donelog .="Send failed with return value = " i " and ErrorLevel = " ErrorLevel "`n"
				msgbox unknown Error:- %i%, error code = %ErrorLevel%   on socket  %iSocket% 
				break
				}                
  			donelog .="Sent " i " bytes! (loop so far)" a_index
          			}
		Else
			{
			donelog .="Sent " i " bytes! (so far)"
			}   
		;Check if everything was sent
		If (i < bSendDataLength - bSendDataSent)
			{
			bSendDataSent += i ;Advance the offset so that at the next iteration, we'll start sending from where we left off
			}
		Else
			{
			donelog .="all sent   `n"
			bSendDataSent := 0
			Break ;We're done
			}
		bSendDataSent := 0
		}
	}

Server(sEvent, iSocket = 0, sName = 0, sAddr = 0, sPort = 0, ByRef bRecvData = 0, bRecvDataLength = 0)
	{
	Global done, recvdtext, sockets_in_use, donelog
	Static bDataSent,count
	donelog .=  " `[email protected]"
	donelog .=sEvent 
	If (sEvent = "ACCEPTED")
		{
		donelog .=  "connection requested " sAddr 
		count=0
		sockets_in_use:=SubStr(sockets_in_use, 1, iSocket - 1) . 1 . SubStr(sockets_in_use,iSocket + 1)
		bDataSent := 0 ;Reset bDataSent for the new client
		donelog .=  " successfully connected on IP " sAddr "on socket"  iSocket "`n"
		done=1
		}
	If (sEvent = "DISCONNECTED")
		{
		done=1
	 	donelog .="The client " sAddr "disconnected `n"
		sockets_in_use:=SubStr(sockets_in_use, 1, (iSocket - 1)) . 0 . SubStr(sockets_in_use, (iSocket + 1))
		}  
  	If (sEvent = "SEND" or sEvent = "SENDLAST")
		{    
        		Loop
			{
			bData:=msg%count%
			bDataLength := StrLen(bData) * 2
			donelog .="trying to send" bData " with a length of "  bDataLength "bytes `n"
			;Try to send the data
			If ((i := AHKsock_Send(iSocket, &bData + bDataSent, bDataLength - bDataSent)) < 0)
				{
				;Check if we received WSAEWOULDBLOCK.
				If (i = -1)
					{
  					;  -1: WSAStartup hasn't been called yet.
					msgbox Error:- %i% WSAStartup hasn't been called yet , error code = %ErrorLevel%   on socket  %iSocket% 
					ExitApp
					}
 				If (i = -2)
					{
					;2: Received WSAEWOULDBLOCK. This means that calling send() would have blocked the thread. we can handle that so add to log
					donelog .="more to send " i 
					Return
					}
  				If (i = -3)
					{
					;-3: The send() call failed. The error is in ErrorLevel.
					msgbox Error:- %i% WSAStartup hasn't been called yet , error code = %ErrorLevel%   on socket  %iSocket% 
					ExitApp
					}
  				If (i = -4)
					{
					;    -4: The socket specified in iSocket is not a valid socket. This means either that the socket in iSocket hasn't been created using AHKsock_Connect or AHKsock_Listen, or that the socket has already been destroyed.
					msgbox Error:- %i% not a valid socket ,error code = %ErrorLevel%   on socket  %iSocket% 
					ExitApp
					}
 				If (i = -5)
					{
					;       -5: The socket specified in iSocket is not cleared for sending. You haven't waited for the SEND event before calling, either ever, or not since you last received WSAEWOULDBLOCK.
					msgbox Error:- %i% Socket is not cleared for sending , error code = %ErrorLevel%   on socket  %iSocket% 
					ExitApp
					}
				If (i < -5 or i > -1)
					{
					donelog .="Send failed with return value = " i " and ErrorLevel = " ErrorLevel "`n"
					msgbox unknown Error:- %i%, error code = %ErrorLevel%   on socket  %iSocket% 
					ExitApp
					}                
				donelog .="Sent " i " bytes! (loop so far)" a_index
          				}
			Else
				{
				donelog .="Sent " i " bytes! (so far)"
				}   
			;Check if everything was sent
			If (i < bDataLength - bDataSent)
				{
				bDataSent += i ;Advance the offset so that at the next iteration, we'll start sending from where we left off
				}
			Else
				{
				donelog .="all sent   `n"
				count+=1
				bDataSent := 0
				if (StrLen(msg%count%)=0)
					{
					Break ;We're done
					}
				}
			bDataSent := 0
			}
		done=1
		}
	If (sEvent = "RECEIVED")
		{
		recvdtext .= bRecvData
		LV_Add("", bRecvData,sAddr,iSocket)
 		donelog .= "recvd this pass:=" bRecvData " in " bRecvDataLength " bytes.`ntotal recvd " recvdtext "`n"
 		done=1
		}
  	If (sEvent = "SENDLAST")
		{
		donelog .="The client " sAddr "is closing ,so clear whats left to send `n"
 		done=1
		}
	if (done<>"1")
		{
		donelog .="Server - Closing"  sAddr "`n"
		If (i := AHKsock_Close(iSocket))
			{
			donelog .="close failed"   ErrorLevel
			sockets_in_use:=SubStr(sockets_in_use, 1, (iSocket - 1)) . 0 . SubStr(sockets_in_use, (iSocket + 1))
			}
		}
	done=
	}
AHKsockErrors(iError, iSocket)
	{
	donelog .="Error " iError " with error code = " ErrorLevel  " on socket " iSocket  "`n"
	detail_msg =
	if (ErrorLevel=6)
		detail_msg =WSA_INVALID_HANDLE.Specified event object handle is invalid.
	if (ErrorLevel=8)
		detail_msg =WSA_NOT_ENOUGH_MEMORY.Insufficient memory available.
	if (ErrorLevel=87)
		detail_msg =WSA_INVALID_PARAMETER.One or more parameters are invalid.
	if (ErrorLevel=995)
		detail_msg =WSA_OPERATION_ABORTED.Overlapped operation aborted.
	if (ErrorLevel=996)
		detail_msg =WSA_IO_INCOMPLETE.Overlapped I/O event object not in signaled state.
	if (ErrorLevel=997)
		detail_msg =WSA_IO_PENDING.Overlapped operations will complete later.
	if (ErrorLevel=10004)
		detail_msg =WSAEINTR.Interrupted function call.
	if (ErrorLevel=10009)
		detail_msg =WSAEBADF.File handle is not valid.
	if (ErrorLevel=10013)
		detail_msg =WSAEACCES.Permission denied.
	if (ErrorLevel=10014)
		detail_msg =WSAEFAULT.Bad address.
	if (ErrorLevel=10022)
		detail_msg =WSAEINVAL.Invalid argument.
	if (ErrorLevel=10024)
		detail_msg =WSAEMFILE.Too many open files.
	if (ErrorLevel=10035)
		detail_msg =WSAEWOULDBLOCK.Resource temporarily unavailable.
	if (ErrorLevel=10036)
		detail_msg =WSAEINPROGRESS.Operation now in progress.
	if (ErrorLevel=10037)
		detail_msg =WSAEALREADY.Operation already in progress.
	if (ErrorLevel=10038)
		detail_msg =WSAENOTSOCK.Socket operation on nonsocket.
	if (ErrorLevel=10039)
		detail_msg =WSAEDESTADDRREQ.Destination address required.
	if (ErrorLevel=10040)
		detail_msg =WSAEMSGSIZE.Message too long.
	if (ErrorLevel=10041)
		detail_msg =WSAEPROTOTYPE.Protocol wrong type for socket.
	if (ErrorLevel=10042)
		detail_msg =WSAENOPROTOOPT.Bad protocol option.
	if (ErrorLevel=10043)
		detail_msg =WSAEPROTONOSUPPORT.Protocol not supported.
	if (ErrorLevel=10044)
		detail_msg =WSAESOCKTNOSUPPORT.Socket type not supported.
	if (ErrorLevel=10045)
		detail_msg =WSAEOPNOTSUPP.Operation not supported.
	if (ErrorLevel=10046)
		detail_msg =WSAEPFNOSUPPORT.Protocol family not supported.
	if (ErrorLevel=10047)
		detail_msg =WSAEAFNOSUPPORT.Address family not supported by protocol family.
	if (ErrorLevel=10048)
		detail_msg =WSAEADDRINUSE.Address already in use.
	if (ErrorLevel=10049 )
		detail_msg =WSAEADDRNOTAVAIL.Cannot assign requested address. 
	if (ErrorLevel=10050)
		detail_msg =WSAENETDOWN.Network is down.
	if (ErrorLevel=10051 )
		detail_msg =WSAENETUNREACH.Network is unreachable.
	if (ErrorLevel=10052 )
		detail_msg =WSAENETRESET.Network dropped connection on reset
	if (ErrorLevel=10053 )
		detail_msg =WSAECONNABORTED. Software caused connection abort.
	if (ErrorLevel=10054 )
		detail_msg = WSAECONNRESET. Connection reset by peer.
	if (ErrorLevel=10055 )
		detail_msg = WSAENOBUFS. No buffer space available.
	if (ErrorLevel=10056 )
		detail_msg =WSAEISCONN. Socket is already connected.
	if (ErrorLevel=10057 )
		detail_msg =WSAENOTCONN. Socket is not connected.
	if (ErrorLevel=10058 )
		detail_msg =WSAESHUTDOWN.Cannot send after socket shutdown.
	if (ErrorLevel=10059 )
		detail_msg =WSAETOOMANYREFS.Too many references.
	if (ErrorLevel=10060 )
		detail_msg =WSAETIMEDOUT. Connection timed out. 
	if (ErrorLevel=10061)
		detail_msg =WSAECONNREFUSED.Connection refused.
	if (ErrorLevel=10062 )
		detail_msg =WSAELOOP.Cannot translate name.
	if (ErrorLevel=10063 )
		detail_msg =WSAENAMETOOLONG. Name too long.
	if (ErrorLevel=10064 )
		detail_msg =WSAEHOSTDOWN. Host is down.
	if (ErrorLevel=10065 )
		detail_msg =WSAEHOSTUNREACH.  No route to host.
	if (ErrorLevel=10066 )
		detail_msg =WSAENOTEMPTY. Directory not empty.
	if (ErrorLevel=10067 )
		detail_msg = WSAEPROCLIM. Too many processes.
	if (ErrorLevel=10068 )
		detail_msg =WSAEUSERS. User quota exceeded.
	if (ErrorLevel=10069 )
		detail_msg =WSAEDQUOT. Disk quota exceeded.
	if (ErrorLevel=10070 )
		detail_msg =WSAESTALE. Stale file handle reference.
	if (ErrorLevel=10071 )
		detail_msg =WSAEREMOTE. Item is remote.
	if (ErrorLevel=10091 )
		detail_msg =WSASYSNOTREADY.Network subsystem is unavailable.
	if (ErrorLevel=10092 )
		detail_msg =WSAVERNOTSUPPORTED. Winsock.dll version out of range.
	if (ErrorLevel=10093 )
		detail_msg =WSANOTINITIALISED. Successful WSAStartup not yet performed.
	if (ErrorLevel=10101 )
		detail_msg =WSAEDISCON. Graceful shutdown in progress.
	if (ErrorLevel=10102 )
		detail_msg =WSAENOMORE. No more results.
	if (ErrorLevel=10103 )
		detail_msg =WSAECANCELLED.Call has been canceled.
	if (ErrorLevel=10104)
		detail_msg =WSAEINVALIDPROCTABLE.Procedure call table is invalid.
	if (ErrorLevel=10105)
		detail_msg =WSAEINVALIDPROVIDER.Service provider is invalid.
	if (ErrorLevel=10106)
		detail_msg =WSAEPROVIDERFAILEDINIT.Service provider failed to initialize.
	if (ErrorLevel=10107)
		detail_msg =WSASYSCALLFAILURE.System call failure.
	if (ErrorLevel=10108)
		detail_msg =WSASERVICE_NOT_FOUND.Service not found.
	if (ErrorLevel=10109)
		detail_msg =WSATYPE_NOT_FOUND.Class type not found.
	if (ErrorLevel=10110)
		detail_msg =WSA_E_NO_MORE.No more results.
	if (ErrorLevel=10111)
		detail_msg =WSA_E_CANCELLED.Call was canceled.
	if (ErrorLevel=10112)
		detail_msg =WSAEREFUSED.Database query was refused.
	if (ErrorLevel=11001)
		detail_msg =WSAHOST_NOT_FOUND.Host not found.
	if (ErrorLevel=11002)
		detail_msg =WSATRY_AGAIN.Nonauthoritative host not found.
	if (ErrorLevel=11003)
		detail_msg =WSANO_RECOVERY.This is a nonrecoverable error.
	if (ErrorLevel=11004)
		detail_msg =WSANO_DATA.Valid name, no data record of requested type.
	if (ErrorLevel>11004 and ErrorLevel<11032)
		detail_msg = WSA_QOS_.......Invalid QoS.......
	; more info available at :-http://msdn.microsoft.com/en-us/library/ms740668
	msgbox Error %iError% with error code = %ErrorLevel%   on socket  %iSocket%- %detail_msg%
	ExitApp
	}
client
#Include %A_ScriptDir%\AHKsock.ahk
#SingleInstance, Off
; multiple clients can run to same or different ports/servers
OnExit, CloseAHKsock
Menu, Tray, Icon ,  ahktcp.ico, 1, 1 
Chr_size=2
if (A_IsCompiled="0" and A_IsUnicode="")
	{
	msgbox "software written for Unicode version need to use a version compiled for Unicode or you will get a The Winsock DLL does not support version 2.2. error"
	ExitApp
	}
sServer =%1%
if (sServer="")
	{
	; you did not send a server IP so i assume you are testing so i will use your ip address for server address
	InputBox, sServer, SERVER ADDRESS, Enter server IP`n(%A_IPAddress1%`n is your IP), , 170, 200, , , , , %A_IPAddress1%
	if ErrorLevel
		ExitApp
	}
sPort =%2%
if (sPort="")
	{
	; you did not send a server Port so i assume you are testing so i will use 27015 for port address
	InputBox, sPort, SERVER PORT, Enter server PORT`n(27015 default), , 170, 200, , , , , 27015
	if ErrorLevel
		ExitApp
	}
; sServer := "localhost"
Gui, Add, ListView, r10 w700 , received|from| on socket
Gui, Add, Edit, vSendthis w300 r1  
Gui, Add, Button, x+1 gGuiSend, Send to server
Gui, Add, Button, x+1 gLog, Log

Gui, Show
msg0=hi ,its me `n
msg1=client msg 1`n
msg2=client msg 2`n
AHKsock_ErrorHandler("AHKsockErrors")
If (i := AHKsock_Connect(sServer, sPort, "Client"))
	{
	If (i = 1)
		{
  		; 1: AHKsock_Connect is still processing a connection attempt. ErrorLevel contains the name and the port of that connection attempt, separated by a tab.
		msgbox Error:- %i% Connect is still processing a connection attempt , error code = %ErrorLevel%   
		ExitApp
		}
	If (i = 2)
		{
  		;     2: sFunction is not a valid function.
		msgbox Error:- %i% sFunction is not a valid function , 
		ExitApp
		}
	If (i = 3)
		{
  		;      3: The WSAStartup() call failed. The error is in ErrorLevel.
		msgbox Error:- %i% The WSAStartup() call failed , error code = %ErrorLevel% 
		ExitApp
		}
	If (i = 4)
		{
  		;         4: The Winsock DLL does not support version 2.2.
		msgbox Error:- %i% The Winsock DLL does not support version 2.2., error code = %ErrorLevel% 
		ExitApp
		}
	If (i = 5)
		{
  		;             5: The getaddrinfo() call failed. The error is in ErrorLevel.
		msgbox Error:- %i% The getaddrinfo() call failed. , error code = %ErrorLevel% 
		ExitApp
		}
	If (i = 6)
		{
  		;           6: The socket() call failed. The error is in ErrorLevel.
		msgbox Error:- %i%  The socket() call failed. , error code = %ErrorLevel% 
		ExitApp
		}
	If (i = 7)
		{
  		;               7: The WSAAsyncSelect() call failed. The error is in ErrorLevel.
		msgbox Error:- %i%  The WSAAsyncSelect() call failed , error code = %ErrorLevel% 
		ExitApp
		}
	If (i = 8)
		{
  		;                  8: The connect() call failed. The error is in ErrorLevel.
		msgbox Error:- %i%  The connect() call failed, error code = %ErrorLevel% 
		ExitApp
		}
	If (i < 1 or i >8)
		{
		donelog .="Send failed with return value = " i " and ErrorLevel = " ErrorLevel "`n"
		msgbox unknown Error:- %i%, error code = %ErrorLevel%   on socket  %mySocket% 
		ExitApp
		}                
	}
; example of sending more ie for network game
sleep 3000
bSendData=client more test
bSendDataLength := StrLen(bSendData)  * Chr_size
sendmore(mySocket , bSendData , bSendDataLength )
sleep 2000
bSendData=client again
bSendDataLength := StrLen(bSendData) * Chr_size
sendmore(mySocket , bSendData , bSendDataLength )
return
log:
msgbox %donelog%
return
GuiSend:
GuiControlGet, Sendthis
bSendData=%Sendthis%
bSendDataLength := StrLen(bSendData)  * Chr_size
sendmore(mySocket , bSendData , bSendDataLength )
return
GuiClose:
ExitApp
return

CloseAHKsock:
AHKsock_Close()
; msgbox %donelog%
; msgbox %recvdtext%
ExitApp
sendmore(iSocket = 0, ByRef bSendData = 0, bSendDataLength = 0)
	{
	Global donelog
	bSendDataSent := 0 
	donelog .=  " `[email protected]"
     	Loop
		{
		donelog .="trying to send" bSendData " with " bSendDataLength "bytes, out on socket " iSocket 
		If ((i := AHKsock_Send(iSocket, &bSendData + bSendDataSent, bSendDataLength - bSendDataSent)) < 0)
			{
			If (i = -1)
				{
  				;  -1: WSAStartup hasn't been called yet.
				msgbox Error:- %i% WSAStartup hasn't been called yet , error code = %ErrorLevel%   on socket  %iSocket% 
				break
				}
 			If (i = -2)
				{
				;2: Received WSAEWOULDBLOCK. This means that calling send() would have blocked the thread. we can handle that so add to log
				donelog .="more to send " i 
				Return
				}
  			If (i = -3)
				{
				;-3: The send() call failed. The error is in ErrorLevel.
				msgbox Error:- %i% WSAStartup hasn't been called yet , error code = %ErrorLevel%   on socket  %iSocket% 
				break
				}
  			If (i = -4)
				{
				;    -4: The socket specified in iSocket is not a valid socket. This means either that the socket in iSocket hasn't been created using AHKsock_Connect or AHKsock_Listen, or that the socket has already been destroyed.
				msgbox Error:- %i% not a valid socket ,error code = %ErrorLevel%   on socket  %iSocket% 
				break
				}
 			If (i = -5)
				{
				;       -5: The socket specified in iSocket is not cleared for sending. You haven't waited for the SEND event before calling, either ever, or not since you last received WSAEWOULDBLOCK.
				msgbox Error:- %i% Socket is not cleared for sending , error code = %ErrorLevel%   on socket  %iSocket% 
				break
				}
			If (i < -5 or i > -1)
				{
				donelog .="Send failed with return value = " i " and ErrorLevel = " ErrorLevel "`n"
				msgbox unknown Error:- %i%, error code = %ErrorLevel%   on socket  %iSocket% 
				break
				}                
  			donelog .="Sent " i " bytes! (loop so far)" a_index
          			}
		Else
			{
			donelog .="Sent " i " bytes! (so far)"
			}   
		;Check if everything was sent
		If (i < bSendDataLength - bSendDataSent)
			{
			bSendDataSent += i ;Advance the offset so that at the next iteration, we'll start sending from where we left off
			}
		Else
			{
			donelog .="all sent   `n"
			bSendDataSent := 0
			Break ;We're done
			}
		bSendDataSent := 0
		}
	}

Client(sEvent, iSocket = 0, sName = 0, sAddr = 0, sPort = 0, ByRef bData = 0, iLength = 0) 
	{
	Global  mySocket, done, recvdtext, donelog, Chr_size
	Static bDataSent, bConnected,count
	donelog .=  " `[email protected]"
	donelog .=sEvent 
	If (sEvent = "CONNECTED")
		{
		donelog .=  "requesting connection " sAddr 
		If (iSocket = -1)
			{
			donelog .=  "request denied " sAddr "`n"
			done=1
			msgbox ,,CONNECTION REQUEST, Not Connected to server (%sAddr%) check server is running,2
			ExitApp
			}
		 Else
			{
			count=0
			bConnected := True
			bDataSent := 0 ;Reset bDataSent
			donelog .=  "request accepted " sAddr " socket" iSocket " Name" sName " Port" sPort "`n"
			done=1
			}
		mySocket := iSocket
		}
	If (sEvent = "DISCONNECTED")
		{
		donelog .=  "disconnected " sAddr "`n"
		done=1
		ExitApp
		}
	If (sEvent = "RECEIVED")
		{
		recvdtext .= bData
		donelog .="recvd:=" bData 
		LV_Add("", bData,sAddr,iSocket)
 		donelog .= "recvd this pass:=" bData " in " bDataLength " bytes.`ntotal recvd " recvdtext "`n"
		done=1
		}
	If (sEvent = "SEND" or sEvent = "SENDLAST")
		{    
        		Loop
			{
			bDatatosend:=msg%count%
			bDataLength := StrLen(bDatatosend) * Chr_size
			donelog .="trying to send" bDatatosend " with a length of "  bDataLength "bytes `n"
			;Try to send the data
			If ((i := AHKsock_Send(iSocket, &bDatatosend + bDataSent, bDataLength - bDataSent)) < 0)
				{
				;Check if we received WSAEWOULDBLOCK.
				If (i = -1)
					{
  					;  -1: WSAStartup hasn't been called yet.
					msgbox Error:- %i% WSAStartup hasn't been called yet , error code = %ErrorLevel%   on socket  %iSocket% 
					ExitApp
					}
	 			If (i = -2)
					{
					;2: Received WSAEWOULDBLOCK. This means that calling send() would have blocked the thread. we can handle that so add to log
					donelog .="more to send " i 
					Return
					}
	  			If (i = -3)
					{
					;-3: The send() call failed. The error is in ErrorLevel.
					msgbox Error:- %i% WSAStartup hasn't been called yet , error code = %ErrorLevel%   on socket  %iSocket% 
					ExitApp
					}
	  			If (i = -4)
					{
					;    -4: The socket specified in iSocket is not a valid socket. This means either that the socket in iSocket hasn't been created using AHKsock_Connect or AHKsock_Listen, or that the socket has already been destroyed.
					msgbox Error:- %i% not a valid socket ,error code = %ErrorLevel%   on socket  %iSocket% 
					ExitApp
					}
 				If (i = -5)
					{
					;       -5: The socket specified in iSocket is not cleared for sending. You haven't waited for the SEND event before calling, either ever, or not since you last received WSAEWOULDBLOCK.
					msgbox Error:- %i% Socket is not cleared for sending , error code = %ErrorLevel%   on socket  %iSocket% 
					ExitApp
					}
				If (i < -5 or i > -1)
					{
					donelog .="Send failed with return value = " i " and ErrorLevel = " ErrorLevel "`n"
					msgbox unknown Error:- %i%, error code = %ErrorLevel%   on socket  %iSocket% 
					ExitApp
					}                
 				}
			Else
				{
				donelog .="Sent " i " bytes! (so far)out of " bDataLength " sent is " bDataSent "`n"
				}   
			;Check if everything was sent
			If (i < bDataLength - bDataSent)
				{
				bDataSent += i ;Advance the offset so that at the next iteration, we'll start sending from where we left off
				donelog .="Sending " i " byte "
				}
			Else
				{
				donelog .="all sent   `n"
				count+=1
				bDataSent := 0
				if (StrLen(msg%count%)=0)
					{
					Break ;We're done
					}
				}
			bDataSent := 0
			}
		done=1
		}
  	If (sEvent = "SENDLAST")
		{
		donelog .="The server " sAddr "is closing ,so clear whats left to send `n"
		}

	if (done<>"1")
		{
		donelog .="Server - Closing"  sAddr
		If (i := AHKsock_Close(iSocket))
			{
			donelog .="close failed AHKsock_Close forcefully closed the socket and freed the associated resources"   ErrorLevel
			bConnected := False
			}
		}
	done=
	return
	}

AHKsockErrors(iError, iSocket)
	{
	donelog .="Error " iError " with error code = " ErrorLevel  " on socket " iSocket  "`n"
	detail_msg =
	if (ErrorLevel=6)
		detail_msg =WSA_INVALID_HANDLE.Specified event object handle is invalid.
	if (ErrorLevel=8)
		detail_msg =WSA_NOT_ENOUGH_MEMORY.Insufficient memory available.
	if (ErrorLevel=87)
		detail_msg =WSA_INVALID_PARAMETER.One or more parameters are invalid.
	if (ErrorLevel=995)
		detail_msg =WSA_OPERATION_ABORTED.Overlapped operation aborted.
	if (ErrorLevel=996)
		detail_msg =WSA_IO_INCOMPLETE.Overlapped I/O event object not in signaled state.
	if (ErrorLevel=997)
		detail_msg =WSA_IO_PENDING.Overlapped operations will complete later.
	if (ErrorLevel=10004)
		detail_msg =WSAEINTR.Interrupted function call.
	if (ErrorLevel=10009)
		detail_msg =WSAEBADF.File handle is not valid.
	if (ErrorLevel=10013)
		detail_msg =WSAEACCES.Permission denied.
	if (ErrorLevel=10014)
		detail_msg =WSAEFAULT.Bad address.
	if (ErrorLevel=10022)
		detail_msg =WSAEINVAL.Invalid argument.
	if (ErrorLevel=10024)
		detail_msg =WSAEMFILE.Too many open files.
	if (ErrorLevel=10035)
		detail_msg =WSAEWOULDBLOCK.Resource temporarily unavailable.
	if (ErrorLevel=10036)
		detail_msg =WSAEINPROGRESS.Operation now in progress.
	if (ErrorLevel=10037)
		detail_msg =WSAEALREADY.Operation already in progress.
	if (ErrorLevel=10038)
		detail_msg =WSAENOTSOCK.Socket operation on nonsocket.
	if (ErrorLevel=10039)
		detail_msg =WSAEDESTADDRREQ.Destination address required.
	if (ErrorLevel=10040)
		detail_msg =WSAEMSGSIZE.Message too long.
	if (ErrorLevel=10041)
		detail_msg =WSAEPROTOTYPE.Protocol wrong type for socket.
	if (ErrorLevel=10042)
		detail_msg =WSAENOPROTOOPT.Bad protocol option.
	if (ErrorLevel=10043)
		detail_msg =WSAEPROTONOSUPPORT.Protocol not supported.
	if (ErrorLevel=10044)
		detail_msg =WSAESOCKTNOSUPPORT.Socket type not supported.
	if (ErrorLevel=10045)
		detail_msg =WSAEOPNOTSUPP.Operation not supported.
	if (ErrorLevel=10046)
		detail_msg =WSAEPFNOSUPPORT.Protocol family not supported.
	if (ErrorLevel=10047)
		detail_msg =WSAEAFNOSUPPORT.Address family not supported by protocol family.
	if (ErrorLevel=10048)
		detail_msg =WSAEADDRINUSE.Address already in use.
	if (ErrorLevel=10049 )
		detail_msg =WSAEADDRNOTAVAIL.Cannot assign requested address. 
	if (ErrorLevel=10050)
		detail_msg =WSAENETDOWN.Network is down.
	if (ErrorLevel=10051 )
		detail_msg =WSAENETUNREACH.Network is unreachable.
	if (ErrorLevel=10052 )
		detail_msg =WSAENETRESET.Network dropped connection on reset
	if (ErrorLevel=10053 )
		detail_msg =WSAECONNABORTED. Software caused connection abort.
	if (ErrorLevel=10054 )
		detail_msg = WSAECONNRESET. Connection reset by peer.
	if (ErrorLevel=10055 )
		detail_msg = WSAENOBUFS. No buffer space available.
	if (ErrorLevel=10056 )
		detail_msg =WSAEISCONN. Socket is already connected.
	if (ErrorLevel=10057 )
		detail_msg =WSAENOTCONN. Socket is not connected.
	if (ErrorLevel=10058 )
		detail_msg =WSAESHUTDOWN.Cannot send after socket shutdown.
	if (ErrorLevel=10059 )
		detail_msg =WSAETOOMANYREFS.Too many references.
	if (ErrorLevel=10060 )
		detail_msg =WSAETIMEDOUT. Connection timed out. 
	if (ErrorLevel=10061)
		detail_msg =WSAECONNREFUSED.Connection refused.
	if (ErrorLevel=10062 )
		detail_msg =WSAELOOP.Cannot translate name.
	if (ErrorLevel=10063 )
		detail_msg =WSAENAMETOOLONG. Name too long.
	if (ErrorLevel=10064 )
		detail_msg =WSAEHOSTDOWN. Host is down.
	if (ErrorLevel=10065 )
		detail_msg =WSAEHOSTUNREACH.  No route to host.
	if (ErrorLevel=10066 )
		detail_msg =WSAENOTEMPTY. Directory not empty.
	if (ErrorLevel=10067 )
		detail_msg = WSAEPROCLIM. Too many processes.
	if (ErrorLevel=10068 )
		detail_msg =WSAEUSERS. User quota exceeded.
	if (ErrorLevel=10069 )
		detail_msg =WSAEDQUOT. Disk quota exceeded.
	if (ErrorLevel=10070 )
		detail_msg =WSAESTALE. Stale file handle reference.
	if (ErrorLevel=10071 )
		detail_msg =WSAEREMOTE. Item is remote.
	if (ErrorLevel=10091 )
		detail_msg =WSASYSNOTREADY.Network subsystem is unavailable.
	if (ErrorLevel=10092 )
		detail_msg =WSAVERNOTSUPPORTED. Winsock.dll version out of range.
	if (ErrorLevel=10093 )
		detail_msg =WSANOTINITIALISED. Successful WSAStartup not yet performed.
	if (ErrorLevel=10101 )
		detail_msg =WSAEDISCON. Graceful shutdown in progress.
	if (ErrorLevel=10102 )
		detail_msg =WSAENOMORE. No more results.
	if (ErrorLevel=10103 )
		detail_msg =WSAECANCELLED.Call has been canceled.
	if (ErrorLevel=10104)
		detail_msg =WSAEINVALIDPROCTABLE.Procedure call table is invalid.
	if (ErrorLevel=10105)
		detail_msg =WSAEINVALIDPROVIDER.Service provider is invalid.
	if (ErrorLevel=10106)
		detail_msg =WSAEPROVIDERFAILEDINIT.Service provider failed to initialize.
	if (ErrorLevel=10107)
		detail_msg =WSASYSCALLFAILURE.System call failure.
	if (ErrorLevel=10108)
		detail_msg =WSASERVICE_NOT_FOUND.Service not found.
	if (ErrorLevel=10109)
		detail_msg =WSATYPE_NOT_FOUND.Class type not found.
	if (ErrorLevel=10110)
		detail_msg =WSA_E_NO_MORE.No more results.
	if (ErrorLevel=10111)
		detail_msg =WSA_E_CANCELLED.Call was canceled.
	if (ErrorLevel=10112)
		detail_msg =WSAEREFUSED.Database query was refused.
	if (ErrorLevel=11001)
		detail_msg =WSAHOST_NOT_FOUND.Host not found.
	if (ErrorLevel=11002)
		detail_msg =WSATRY_AGAIN.Nonauthoritative host not found.
	if (ErrorLevel=11003)
		detail_msg =WSANO_RECOVERY.This is a nonrecoverable error.
	if (ErrorLevel=11004)
		detail_msg =WSANO_DATA.Valid name, no data record of requested type.
	if (ErrorLevel>11004 and ErrorLevel<11032)
		detail_msg = WSA_QOS_.......Invalid QoS.......
	; more info available at :-http://msdn.microsoft.com/en-us/library/ms740668
	msgbox Error %iError% with error code = %ErrorLevel%   on socket  %iSocket%- %detail_msg%
	ExitApp
	}


chippp
  • Members
  • 1 posts
  • Last active: Nov 06 2012 10:04 AM
  • Joined: 04 Nov 2012
Hi
Who has all the code examples or some of them at least and ahksock for ansi?
Thanks!

TheGood
  • Members
  • 589 posts
  • Last active: Mar 22 2014 03:22 PM
  • Joined: 30 Jul 2007

I've re-uploaded the scripts and updated the first post.

It's just the Unicode version for now. I'll see if I can dig up the ANSI version as well.



stevenp
  • Members
  • 197 posts
  • Last active: Sep 23 2014 05:47 PM
  • Joined: 28 Aug 2006

is it possible to make a connection between various scripting languages, e.g. python, php, java?

or is it only for an ahk-to-ahk communication?


"Simplifying complexity is not simple"

TheGood
  • Members
  • 589 posts
  • Last active: Mar 22 2014 03:22 PM
  • Joined: 30 Jul 2007

is it possible to make a connection between various scripting languages, e.g. python, php, java?

or is it only for an ahk-to-ahk communication?

 

You can do whatever you want! e.g. the client in AHK and the server in python.

As long as they both "speak" the same protocol (either a known one or one you made up), there shouldn't be any issue at all.

For example, in the file sending example, it should be pretty trivial to write a client in another language that does the same thing.



Leef_me
  • Moderators
  • 8510 posts
  • Last active: Sep 10 2015 05:50 AM
  • Joined: 08 Apr 2009

In the Example 3 chatting example there is a routine ,AddDialog, I want to inspect the data sent from the peer

but I can't figure out how to read the data referenced by "ptrText"

 

My desire is to detect when a "http" string is sent.

 

 

When the receiving routine gets the data it specifies "false" for bYou which means "not you" therefore "peer"

 AddDialog(&sTextData, False)
 

 

AddDialog(ptrText, bYou = True) {
    Global htxtDialog
   
    ;Append the interlocutor
    sAppend := bYou ? "You > " : "Peer >!! "
    InsertText(htxtDialog, &sAppend)
   
    ;Append the new text
    InsertText(htxtDialog, ptrText)

 

    ;Append a new line
    sAppend := "`r`n"

 

    InsertText(htxtDialog, &sAppend)

   
    ;Scroll to bottom
    SendMessage, 0x0115, 7, 0,, ahk_id %htxtDialog% ;WM_VSCROLL
}

 

 

Any help appreciated.



TheGood
  • Members
  • 589 posts
  • Last active: Mar 22 2014 03:22 PM
  • Joined: 30 Jul 2007

In the Example 3 chatting example there is a routine ,AddDialog, I want to inspect the data sent from the peer

but I can't figure out how to read the data referenced by "ptrText"

 

My desire is to detect when a "http" string is sent.

 

Hey Leef_me,

I think you can use StrGet() for that now.

Previously (in older version of AHK) you would use a trick like MulDiv as shown here.

 

Note that if you're trying to communicate with an HTTP server, you don't need all the stuff with prepending the length and the typing updates. If you just want to telnet/have a raw TCP session, you just need to send the command (eg "GET index http/1.1") followed by /n.



wnltl
  • Members
  • 8 posts
  • Last active: May 09 2013 01:20 PM
  • Joined: 12 Jun 2012

ahksock is very nice library!

and LARK2355  yours script  It was help for me. Thanks

tongue.png



tsugua
  • Members
  • 2 posts
  • Last active: Feb 18 2013 08:04 PM
  • Joined: 17 Feb 2013

Hi, I'm very new to AHK and I'm having a bit of trouble. I posted my question in another part of the forum so I thought I would reference it here:

 

http://www.autohotke...nd/#entry571329



djvj
  • Members
  • 70 posts
  • Last active: Jul 22 2016 02:54 AM
  • Joined: 19 Sep 2010

I spent all night tracking this down, but here is the x86 ANSI version of the AHKsock.ahk (found it on a japanese website):

 

http://pastebin.com/q5AE63JY



iDrug
  • Members
  • 389 posts
  • Last active: Oct 11 2015 09:24 PM
  • Joined: 13 Oct 2009
Why's that not working?
#Persistent
AHKsock_Listen(9, notify) ; I've also tried AHKsock_Listen(9, "notify")

notify()
{
msgbox port 9 received a packet!
}
Could someone help me? I've read the functions documentation, but that didn't help.
I need a simple script that listens to the incoming packets on a specific port and throws a messagebox upon receiving any packets.
How to do that? it should be easy, but I didn't manage to make it work with these functions.