2 Way Realtime communication between 2 AHK scripts [IRC/WebSocket/WinSock]

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
User avatar
labrint
Posts: 383
Joined: 14 Jun 2017, 05:06
Location: Malta

2 Way Realtime communication between 2 AHK scripts [IRC/WebSocket/WinSock]

01 Apr 2022, 09:32

Hi guys,

I am developing a small script to act as a prescription software for a doctor in one of our clinics.

I need a way to confirm the availability of the items in a listbox on the doctor's script.

How can I confirm/accept/reply if unavailable from my script?
Last edited by labrint on 04 Apr 2022, 02:07, edited 2 times in total.
murataygun
Posts: 104
Joined: 07 Aug 2015, 15:53

Re: 2 Way chat

01 Apr 2022, 10:22

May write a back end for this. Or use websocket if it has to be realtime.
User avatar
labrint
Posts: 383
Joined: 14 Jun 2017, 05:06
Location: Malta

Re: 2 Way chat

01 Apr 2022, 10:30

murataygun wrote:
01 Apr 2022, 10:22
May write a back end for this. Or use websocket if it has to be realtime.
I'm going to need a simple example because I have never used websocket. Basically I simply need to either confirm the contents of a listbox are available, and if not reply a message. So yes the message and confirmation need to be realtime.

Do you know how to do this? @G33kDude @geek

Here is my prescription script. Need a way to confirm the contents of the list box before printing the prescription. If the item is not available I want to be able to send back an alternative and let the doctor confirm.

Code: Select all

#NoEnv  ; Recommended for performance and compatibility with future AutoHotkey releases.
; #Warn  ; Enable warnings to assist with detecting common errors.
SendMode Input  ; Recommended for new scripts due to its superior speed and reliability.
SetWorkingDir %A_ScriptDir%  ; Ensures a consistent starting directory.
#SingleInstance force
#Persistent

FormatTime, Date, %Date%, dd/MM/yyyy
FormatTime, DateNTime, %DateNTime%, dd/MM/yyyy HH:mm:ss


IniRead, PatientNames, C:\Prescriptions\Prescriptions.ini

Loop, Parse, PatientNames,`n
{
PN := RegExMatch(A_Loopfield, "(.*)?\t", PatientNamesParsed)



If PatientNamesDelimited =
PatientNamesDelimited .= PatientNamesParsed1

Else If PatientNamesDelimited !=
PatientNamesDelimited .= "|" PatientNamesParsed1
}

FileRead, DrugNames, C:\Prescriptions\DailiesRegister.csv

Loop, Parse, DrugNames,`n
{

	Loop, Parse, A_Loopfield, CSV
	{
		If A_Index = 3
		{
		DrugWOSpaces := RegExReplace(A_Loopfield,"\s+$","")
		
		If DrugNamesDelimited =
		DrugNamesDelimited .= DrugWOSpaces

		Else If DrugNamesDelimited !=
		DrugNamesDelimited .= "|" DrugWOSpaces
		}
	}
}


Gui, Add, Text,, Patient Name, Surname, ID (eg. John Agius 0126457M)
Gui, Add, ComboBox, vComboBox gCbAutoComplete w200 Uppercase,
Gui, Add, Text,, Drug (including dose)
Gui, Add, ComboBox, vComboBox2 hwndLB gCbAutoComplete w200 h50 Uppercase,
Gui, Add, Text,xm, Dosing Schedule (eg. 1-0-1)
Gui, Add, Edit,xm vDosingSchedule w200 Uppercase, 
Gui, Add, Button, x+5 gAdd w60 h20, Add
Gui, Add, ListBox,xm r6 vListBox hwndHListbox w200,
Gui, Add, Button,x+5 w60 h20 gRemove, Remove
Gui, Add, Text,xm, Date
Gui, Add, Edit,w200 Uppercase, %Date%
Gui, Add, Text,xm, Doctor Name & Reg No
Gui, Add, Edit,w200 h50 Uppercase vDrCred, DR JOSEPH ZAMMIT`nREG NO.1689`nSAN RAFFAEL PHARMACY`, MARSA`nMONDAY-FRIDAY 10AM-12PM SATURDAY 12PM-1PM`nMOB: 99 470 827
Gui, Add, Button, x+5 w60 h50 gPrint, Print

GuiControl,, ComboBox, |%PatientNamesDelimited%
GuiControl,, ComboBox2, |%DrugNamesDelimited%

Gui, Show
Return

Print:
Gui, Submit, NoHide
While FileExist( "C:\Prescriptions\Rx.rtf" )
{
  Sleep 250
  FileDelete, C:\Prescriptions\Rx.rtf
}

dir = C:\Prescriptions
If !FileExist(dir) {
 FileCreateDir, %dir%
 If ErrorLevel
  {}
 Else {}
}

ControlGet, ListBox, List, , , ahk_id %HListbox%
ListBox := RegExReplace(ListBox, "\n", "|")
IniWrite, %ListBox%, C:\Prescriptions\Prescriptions.ini, %ComboBox%`t%DateNTime%, Prescription

ListBox := RegExReplace(ListBox, "\|", "`n")

FR := RegExMatch(ListBox, "[a-zA-Z0-9]", hastext)

If FR = 0
Reload

Loop, Parse, DrCred, `n
{
If A_Index = 1
DrName := A_Loopfield

If A_Index = 2
DrReg := A_Loopfield

If A_Index = 5
ContactDetails := A_Loopfield
}

ComboBox := RegExReplace(ComboBox, """", "")
DateNTime := RegExReplace(DateNTime, """", "")
ListBox := RegExReplace(ListBox, """", "")
DrName := RegExReplace(DrName, """", "")
DrReg := RegExReplace(DrReg, """", "")

Loop, Parse, ListBox, `n
{
FM := RegExMatch(A_Loopfield,"(.*)?(?:\t){1,50}(.*)",Posology)

FileAppend, "%ComboBox%"`,"%DateNTime%"`,"%Posology1%"`,"%Posology2%"`,"%DrName%"`,"%DrReg%"`n, C:\Prescriptions\DailiesRegister.csv
}

Sleep, 50

GoSub, PrintRx
Reload
Return

PrintRx:
RTFFunction(DateNTime,ComboBox,ListBox,DrCred)
Return





Add:
Gui, Submit, NoHide

If ComboBox2 =
Return

ControlGet, ListBox, List, , , ahk_id %HListbox%

FR := RegExMatch(ListBox, "[a-zA-Z0-9]", hastext)

If FR = 0
ListBox :=

ListBox := RegExReplace(ListBox, "\n", "|")

If FR = 0
ListBox .= ComboBox2 "		" DosingSchedule

If FR !=0
ListBox .= "|" ComboBox2 "	" DosingSchedule

GuiControl,,ListBox,|%ListBox%
GuiControl,,DosingSchedule
GuiControl, Choose, ComboBox2, 0
ControlFocus, ComboBox2
Return

Remove:
Gui, Submit, NoHide

If ListBox =
Return

ListBoxSelected := ListBox

ControlGet, ListBox, List, , , ahk_id %HListbox%

ListBox := RegExReplace(ListBox, ListBoxSelected "(\n|)", "")
ListBox := RegExReplace(ListBox, "\n", "|")

GuiControl,,ListBox,|%ListBox%
Return





RTFFunction(DateNTime,ComboBox,ListBox,DrCred){

ListBoxPrintOut := RegExReplace(ListBox, "\n", "\par`n\par`n")
ListBoxPrintOut := RegExReplace(ListBoxPrintOut, "\t+", "\par`n")
ListBoxPrintOut := ListBoxPrintOut "\par`n"

Loop, Parse, DrCred, `n
{
If A_Index = 1
DrName := A_Loopfield

If A_Index = 2
DrReg := A_Loopfield

If A_Index = 3
DrPharmacy := A_Loopfield

If A_Index = 4
DrSchedule := A_Loopfield

If A_Index = 5
ContactDetails := A_Loopfield
}

RTFBase =
(
{\rtf1\ansi\ansicpg1252\deff0\nouicompat\deflang2057{\fonttbl{\f0\fnil\fcharset0 Calibri;}}
{\*\generator Riched20 10.0.19041}\viewkind4\uc1 
\pard\sa200\sl276\slmult1\qr\b\f0\fs22\lang9 %DateNTime%\par

\pard\sa200\sl240\slmult1\i\fs72 R\sub x\nosupersub\i0\fs22\par

\pard\sa200\sl276\slmult1\qc %ComboBox%\par

\pard\sa200\sl276\slmult1\par

\pard\sa200\sl276\slmult1\qc %ListBoxPrintOut%

\pard\sa200\sl276\slmult1\par

\pard\sl360\slmult1\fs18 %DrName%\par
%DrReg%\par
\fs14 %DrPharmacy%\fs18\par
\fs14 %DrSchedule%\par
\fs18 %ContactDetails%\par
}
)

FileAppend, %RTFBase%, C:\Prescriptions\Rx.rtf
}




/*
	=======================================================================================
	 Function:			SHAutoComplete
	 Description:		Auto-completes typed values in an edit with various options.
	 Usage:
		Gui, Add, Edit, w200 h21 hwndEditCtrl1
		SHAutoComplete(EditCtrl1)
	=======================================================================================
*/
SHAutoComplete(hEdit, Option := 0x20000000) {
	; https://bit.ly/335nOYt		For more info on the function.
	DllCall("ole32\CoInitialize", "Uint", 0)
	; SHACF_AUTOSUGGEST_FORCE_OFF (0x20000000)
	;	Ignore the registry default and force the AutoSuggest feature off.
	;	This flag must be used in combination with one or more of the SHACF_FILESYS* or SHACF_URL* flags.
	; AKA. It won't autocomplete anything, but it will allow functionality such as Ctrl+Backspace deleting a word.
	DllCall("shlwapi\SHAutoComplete", "Uint", hEdit, "Uint", Option)
	DllCall("ole32\CoUninitialize")
}

/*
	=======================================================================================
	 Function:			CbAutoComplete
	 Description:		Auto-completes typed values in a ComboBox.

	 Author:			Pulover [Rodolfo U. Batista]
	 Usage:
		Gui, Add, ComboBox, w200 h50 gCbAutoComplete, Billy|Joel|Samual|Jim|Max|Jackson|George
	=======================================================================================
*/
CbAutoComplete() {
	; CB_GETEDITSEL = 0x0140, CB_SETEDITSEL = 0x0142
	If ((GetKeyState("Delete", "P")) || (GetKeyState("Backspace", "P")))
		Return
	GuiControlGet, lHwnd, Hwnd, %A_GuiControl%
	SendMessage, 0x0140, 0, 0,, ahk_id %lHwnd%
	MakeShort(ErrorLevel, Start, End)
	GuiControlGet, CurContent,, %lHwnd%
	GuiControl, ChooseString, %A_GuiControl%, %CurContent%
	If (ErrorLevel) {
		ControlSetText,, %CurContent%, ahk_id %lHwnd%
		PostMessage, 0x0142, 0, MakeLong(Start, End),, ahk_id %lHwnd%
		Return
	}
	GuiControlGet, CurContent,, %lHwnd%
	PostMessage, 0x0142, 0, MakeLong(Start, StrLen(CurContent)),, ahk_id %lHwnd%
}

; Required for: CbAutoComplete()
MakeLong(LoWord, HiWord) {
	Return, (HiWord << 16) | (LoWord & 0xffff)
}

; Required for: CbAutoComplete()
MakeShort(Long, ByRef LoWord, ByRef HiWord) {
	LoWord := Long & 0xffff, HiWord := Long >> 16
}









User avatar
labrint
Posts: 383
Joined: 14 Jun 2017, 05:06
Location: Malta

Re: 2 Way chat - Realtime communication between 2 AHK scripts

04 Apr 2022, 01:33

I found this code by @wankausr for a TCP/IP Server and Client. Could be useful for my project. It used to work in the past but now its giving me an error: connect() indicated Winsock error 10051?

Link to other thread: https://www.autohotkey.com/board/topic/29650-tcpip-serverclient-chat-script-w-features/page-7
A link to another thread (WinSock): https://www.autohotkey.com/board/topic/53827-ahksock-a-simple-ahk-implementation-of-winsock-tcpip/
And another: viewtopic.php?f=6&t=35242&p=162509

Here is the code by @wankausr :

Server code :

Code: Select all

#singleinstance force
#Persistent
;#notrayicon

logedin=0
logo=
(
~~~~~Welcome to Winsock-Chat!~~~~~
To register use
/reg username@password
)
ifnotexist,Settings
{
Filecreatedir,Settings
}
ifnotexist,Settings\logo.txt
{

logo:=Enc_Hex(logo)
fileappend,%logo%,Settings\logo.txt
}
else
fileread,logo,Settings\logo.txt
ifnotexist,Settings\users.ini
iniwrite, password,Settings\users.ini, Users,Anonimus
Network_Address = 0.0.0.0
Network_Port = 1000

menu, tray, tip, Listening on`nIP: %A_Ipaddress1%`nPort: %Network_Port%
menu, tray, icon, %a_windir%\explorer.exe
menu, tray, nostandard
menu, tray, add, Restart
menu, tray, add, EditLogo
menu, tray, add, Show
menu, tray, add, Exit

colordef=C0C0C0
gui, color, %colordef%
Gui, Add, Edit, x6 y5 w360 h190 readonly vchat, 
Gui, Add, Edit, x376 y5 w110 h150 readonly vchatlist, 
Gui, Add, Edit, x6 y204 w210 h20 vSendText, 
Gui, Add, Button, x226 y204 w70 h20 vSendviaNet gSendviaNet, Send
Gui, Add, Button, x6 y204 w296 h20 vstartsvr gstartsvr, Start Server
Gui, Add, edit, x306 y204 w70 h20 vkicknick, 
Gui, Add, Button, x386 y204 w40 h20 vkick gkick_player, Kick
Gui, Add, Button, x446 y204 w40 h20 vKILL gkill, KILL
Gui, Add, Button, x376 y165 w110 h30 , Hide
;guicontrol,disable, kicknick
;guicontrol,disable, kick
Gui, Show, x135 y95 h233 w501, WinSock Chat Server
WinGet Gui_ID, ID, WinSock Chat Server
;Menu, OptionsMenu, Add, &Restart, Restart
;Menu, OptionsMenu, Add, &Edit Logo,EditLogo
;Menu, OptionsMenu, Add, &Hide,buttonhide
;Menu, FileMenu, Add, E&xit, Exit
;Menu, MyMenuBar, Add, &File, :FileMenu  
;Menu, MyMenuBar, Add, &Options, :OptionsMenu
;Gui, Menu, MyMenuBar
;guicontrol,disable, kicknick
;guicontrol,disable, kick
guicontrol, hide, startsvr
Gui, Show, x135 y95 h233 w501, Server
WinGet Gui_ID, ID, Server

Gosub Connection_Init

return

buttonhide:
winhide, Server
return

Show:
winshow, Server
   controlsend edit1, ^{end}, Server
return

$Enter::
ifwinactive, Server
{
gosub, SendviaNet
}
else
send, {ENTER}
return

Connection_Init:
OnExit, ExitSub  


socket := PrepareForIncomingConnection(Network_Address, Network_Port)
if socket = -1  
    ExitApp

Process, Exist 
DetectHiddenWindows On
ScriptMainWindowId := WinExist("ahk_class AutoHotkey ahk_pid " . ErrorLevel)
DetectHiddenWindows Off


NotificationMsg = 0x5555  

OnMessage(NotificationMsg, "ReceiveData")


FD_READ = 1     
FD_CLOSE = 32   
FD_CONNECT = 20 


if DllCall("Ws2_32\WSAAsyncSelect", "UInt", socket, "UInt", ScriptMainWindowId, "UInt", NotificationMsg, "Int", FD_READ|FD_CONNECT)
{
    MsgBox % "WSAAsyncSelect() indicated Winsock error " . DllCall("Ws2_32\WSAGetLastError")
    ExitApp
}



i=1
Loop 
{
    VarSetCapacity(SocketAddress, SizeOfSocketAddress:=16)
    conectioncheck%i% := DllCall("Ws2_32\accept", "UInt", socket, "UInt", &SocketAddress, "Int*", SizeOfSocketAddress)
    if conectioncheck%i% != -1
    {
        i++
        peername := DllCall("Ws2_32\inet_ntoa", "uint", NumGet(SocketAddress,4), "str")
            . ":" NumGet(SocketAddress,2,"ushort")
           fileappend, %peername% connecting...`n,Settings\server.txt
   fileread, chat2,Settings\server.txt
   guicontrol,,chat, %chat2%
   controlsend edit1, ^{end}, Server
   Sendtext= RX2CLIENTCON:
   gosub, Send1
   ;sleep 100
   ;Sendtext=LOGO:%logo%
   ;gosub, send1
   ;Sendtext=
    }
    sleep 500 
}   
return

SendviaNet:
Gui, Submit, NoHide
SendText =$ChatServer: %SendText%
guicontrol,,SendText,
go:
fileappend, %SendText%`n,Settings\server.txt
   fileread, chat2,Settings\server.txt
   guicontrol,,chat, %chat2%
   controlsend edit1, ^{end}, Server
gosub, send1
resend:
SendText= %ShowRecieved%
ShowRecieved=
send1:
Loop %i% {
   SendData(conectioncheck%A_Index%,SendText)
}
SendText =
return



PrepareForIncomingConnection(IPAddress, Port)
{
    VarSetCapacity(wsaData, 32)  
    result := DllCall("Ws2_32\WSAStartup", "UShort", 0x0002, "UInt", &wsaData) ; Request Winsock 2.0 (0x0002)
   
    if ErrorLevel
    {
        MsgBox WSAStartup() could not be called due to error %ErrorLevel%. Winsock 2.0 or higher is required.
        return -1
    }
    if result 
    {
        MsgBox % "WSAStartup() indicated Winsock error " . DllCall("Ws2_32\WSAGetLastError")
        return -1
    }

    AF_INET = 2
    SOCK_STREAM = 1
    IPPROTO_TCP = 6
    socket := DllCall("Ws2_32\socket", "Int", AF_INET, "Int", SOCK_STREAM, "Int", IPPROTO_TCP)
    if socket = -1
    {
        MsgBox % "socket() indicated Winsock error " . DllCall("Ws2_32\WSAGetLastError")
        return -1
    }


    SizeOfSocketAddress = 16
    VarSetCapacity(SocketAddress, SizeOfSocketAddress)
    InsertInteger(2, SocketAddress, 0, AF_INET)   ; sin_family
    InsertInteger(DllCall("Ws2_32\htons", "UShort", Port), SocketAddress, 2, 2)   ; sin_port
    InsertInteger(DllCall("Ws2_32\inet_addr", "Str", IPAddress), SocketAddress, 4, 4)   ; sin_addr.s_addr

    if DllCall("Ws2_32\bind", "UInt", socket, "UInt", &SocketAddress, "Int", SizeOfSocketAddress)
    {
        MsgBox % "bind() indicated Winsock error " . DllCall("Ws2_32\WSAGetLastError") . "?"
        return -1
    }
    if DllCall("Ws2_32\listen", "UInt", socket, "UInt", "SOMAXCONN")
    {
        MsgBox % "LISTEN() indicated Winsock error " . DllCall("Ws2_32\WSAGetLastError") . "?"
        return -1
    }
    
    return socket  
}


ReceiveData(wParam, lParam)

{
Critical
   global ShowRecieved
    socket := wParam
    ReceivedDataSize = 4096 
    Loop  
    {
        VarSetCapacity(ReceivedData, ReceivedDataSize, 0) 
        ReceivedDataLength := DllCall("Ws2_32\recv", "UInt", socket, "Str", ReceivedData, "Int", ReceivedDataSize, "Int", 0)
        if ReceivedDataLength = -1
        {
            WinsockError := DllCall("Ws2_32\WSAGetLastError")
            if WinsockError = 10035 
                return 1
            if WinsockError <> 10054 
               
MsgBox % "recv() indicated Winsock error " . WinsockError           
ExitApp  
        }
      

        Loop, parse, ReceivedData, `n, `r
        {
           ShowRecieved = %ShowRecieved%%A_LoopField%
   ifnotinstring, Showrecieved, :
{
gosub, redirects
}

ifnotinstring , Showrecieved, LOGO
   fileappend, %ShowRecieved%`n,Settings\server.txt
   fileread, chat2,Settings\server.txt
   guicontrol,,chat, %chat2%
   controlsend edit1, ^{end}, Server
          gosub, resend
   ;ShowRecieved =
        }
    }
    return 1 
}

SendData(wParam,SendData)
{
socket := wParam
;fileappend, %socket%`n,Settings\testing.txt
SendDataSize := VarSetCapacity(SendData)
SendDataSize += 1
sendret := DllCall("Ws2_32\send", "UInt", socket, "Str", SendData, "Int", SendDatasize, "Int", 0)
;send( sockConnected,> welcome, strlen(welcome) + 1, NULL);
}

redirects:
;msgbox %Showrecieved%
ifinstring, Showrecieved, DOLOGIN1
{
;msgbox %Showrecieved%
StringSplit, recievedx, Showrecieved,@
Stringreplace, recievedx2, recievedx2, DOLOGIN1
Stringreplace, recievedx2, recievedx2,%a_space% 
iniread, pass,Settings\users.ini, Users, %recievedx1%
data:=recievedx2
;msgbox %pass%=%data%
if ( pass = data )
{
ShowRecieved=
(
LOGO%logo%
)
;return
}
else
{
ShowRecieved=%recievedx1% notvaliduserorpass!

;ShowRecieved=SR1NONUSER:
;sssssss=
;return
}
return
}

ifinstring, Showrecieved, kicked!
{
return
}
ShowRecieved2=%ShowRecieved%
;msgbox %ShowRecieved2%
Stringreplace, Showrecieved2, Showrecieved2, %A_Space%, `n, 
filedelete,Settings\usertemp.txt
fileappend, %ShowRecieved2%,Settings\usertemp.txt
filereadline, name1,Settings\usertemp.txt,1
filereadline, cord,Settings\usertemp.txt,2
filedelete,Settings\usertemp.txt
if cord=connected!
{
fileappend, %name1%`n, Settings\userlist.txt
fileread, userlist, Settings\userlist.txt
guicontrol,,chatlist, %userlist%
stringreplace,userlist,userlist,`n,*,All
sleep, 500
Sendtext=SR1CLIENTADDLIST%userlist%
gosub, send1
name1=
cord=
return
}
/*
if cord=notvaliduserorpass!
{
Sendtext=SR1NONUSER
gosub, send1
name1=
cord=
return
}
*/
if cord=disconnected!
{
fileread, dellist,Settings\userlist.txt
stringreplace, dellist2, dellist, %name1%`r`n
filedelete, Settings\userlist.txt
fileappend, %dellist2%,Settings\userlist.txt
fileread, userlist,Settings\userlist.txt
guicontrol,,chatlist, %userlist%
stringreplace,userlist,userlist,`n,*,All
Sendtext=SR1CLIENTADDLIST%userlist%
gosub, send1
name1=
cord=
return
}
ifinstring, Showrecieved,/reg
{
;msgbox %Showrecieved%
Stringreplace, Showrecieved, Showrecieved,/reg
StringSplit, recievedx, Showrecieved,%a_space%
StringSplit, recievedx2, Showrecieved,@,%a_space%
iniread, isuser,Settings\users.ini, Users, %recievedx21%
if isuser<> ERROR
ShowRecieved=%recievedx21% is already a registered user!
else
{
if isuser= recievedx22
ShowRecieved=%recievedx21% you are already registered!
else
{
iniwrite, %recievedx22%,Settings\users.ini, Users,%recievedx21%
ShowRecieved=%recievedx21% is now a registered user!
}
}
return
}
ifinstring, Showrecieved,/w
return



InsertInteger(pInteger, ByRef pDest, pOffset = 0, pSize = 4)
{
    Loop %pSize%  
        DllCall("RtlFillMemory", "UInt", &pDest + pOffset + A_Index-1, "UInt", 1, "UChar", pInteger >> 8*(A_Index-1) & 0xFF)
}

kick_player:
gui, submit, nohide
guicontrol,,kicknick,
ref=
Sendtext=RX2KICKPLAYER%kicknick%
gosub, send1
sleep, 500
fileread, dellist,Settings\userlist.txt
stringreplace, dellist2, dellist, %kicknick%|
filedelete,Settings\userlist.txt
fileappend, %dellist2%,Settings\userlist.txt
fileread, userlist,Settings\userlist.txt
guicontrol,,chatlist, |%userlist%
stringreplace,userlist,userlist,|,*,All
Sendtext=SR1LOGIN0SR1CLIENTADDLIST%userlist%
gosub, send1
sendtext=
name1=
kicknick=
cord=
return

restart:
filedelete,Settings\server.txt
filedelete,Settings\userlist.txt
DllCall("Ws2_32\WSACleanup")
reload

editlogo:
;msgbox,16,Server, You have to restart the app before the logo changes work!
gui,10: +owner
gui,10: color, %colordef%
xlogo:=Dec_Hex(logo)
Gui,10: Add, Edit, x6 y7 w420 h230 veditlogo, %xlogo%
Gui,10: Add, Button, x6 y247 w160 h20 gcancelbtn, Cancel
Gui,10: Add, Button, x246 y247 w170 h20 gsavebtn, Save
; Generated using SmartGUI Creator 4.0
Gui,10: Show, x131 y91 h274 w437,Edit Server Logo
Return

cancelbtn:
gui 10:destroy
return

savebtn:
gui 10:submit, nohide
logo:=Enc_Hex(editlogo)
filedelete , Settings\logo.txt
fileappend ,%logo%,Settings\logo.txt
gui,10:destroy
return


usropt:
If A_GuiEvent=DoubleClick
{
Menu, MyMenu, Add, Kick, kick
Menu, MyMenu, Show
}
return

kick:
Gui,Submit,NoHide
kicknick=%chatlist%
Sendtext=Admin is kicking %kicknick%
gosub, send1
sleep, 5000
ref=
Sendtext=RX2KICKPLAYER%kicknick%
gosub, send1
sleep, 500
fileread, dellist,Settings\userlist.txt
stringreplace, dellist2, dellist, %kicknick%|
filedelete,Settings\userlist.txt
fileappend, %dellist2%,Settings\userlist.txt
fileread, userlist,Settings\userlist.txt
guicontrol,,chatlist, |%userlist%
stringreplace,userlist,userlist,|,*,All
Sendtext=SR1LOGIN0SR1CLIENTADDLIST%userlist%
gosub, send1
sendtext=
name1=
kicknick=
cord=
return


Exit:
exitapp
ExitSub:  
gui, submit, nohide
if chatlist=
{
goto, end
}
Msgbox, 48, Server, Server will shut down 5 second(s) after you hit ok!
gui, destroy
Sendtext= Server is Shutting down in 5 Second(s)
gosub, send1
sleep, 5000
end:
filedelete,Settings\server.txt
filedelete,Settings\userlist.txt
DllCall("Ws2_32\WSACleanup")
ExitApp

guiclose:
filedelete,Settings\userlist.txt
filedelete,Settings\server.txt
exitapp

kill:
kill_cons()
return

startsvr:
reload
return

Enc_Hex(x) ;originally: String2Hex(x) ; Convert a string to hex digits (modified to accommodate new line chars)
{
   prevFmt = %A_FormatInteger%
   SetFormat Integer, H ; this function requires hex format
   Loop Parse, x
      hex .= 0x100+Asc(A_LoopField)
   StringReplace hex, hex, 0x1,,All
   SetFormat Integer, %prevFmt% ; restore original integer formatting
   Return hex
}

Dec_Hex(x) ;originally: Hex2String(x) ; Convert a huge hex number to string (modified to suit String2Hex above)
{
   Loop % StrLen(x)/2
   {
      Pos:=(A_Index-1)*2+1
      StringMid hex, x, Pos, 2
      string := string . Chr("0x" hex)
   }
   Return string
}

kill_cons()
{
DllCall("Ws2_32\WSACleanup")
guicontrol,,chat, Server status: OFFLINE
guicontrol,,chatlist, 
filedelete,Settings\userlist.txt
filedelete,Settings\server.txt
guicontrol, hide, SendText
guicontrol, hide, SendviaNet
guicontrol, show, startsvr
DllCall("ws2_32\closesocket", "uint", socket)
}
Client code:

Code: Select all

;#singleinstance force
#singleinstance off
#Persistent
#MaxMem 256 
;#notrayicon
ifnotexist,Settings
{
Filecreatedir,Settings
}
configurex=1
menu, tray, icon, %A_Windir%\system32\narrator.exe
menu, tray, nostandard
menu, tray, add, Hide
menu, tray, add, Configure
menu, tray, add, Exit
filedelete,Settings\i2l.txt
filedelete,Settings\usernamestemp.txt


on=0
checkornot=0
con=0
end=0
las=1
ClientName=Anonimus
ClientPass=password
Network_Address = 127.0.0.1
Network_Port = 1000
ifexist,Settings\clientinfo.ini
{
iniread, Network_address,Settings\clientinfo.ini, Info, ip
iniread, Network_port,Settings\clientinfo.ini, Info, port
iniread, ClientName,Settings\clientinfo.ini, User, name
iniread, ClientPass,Settings\clientinfo.ini, User, pass
}
else
{
iniwrite, %Network_address%,Settings\clientinfo.ini, Info, ip
iniwrite, %Network_port%,Settings\clientinfo.ini, Info, port
iniwrite, Anonimus,Settings\clientinfo.ini, User, name
iniwrite, password,Settings\clientinfo.ini, User, pass
}
menu, tray, tip, Currently Set to`nIP: %Network_Address%`nPort: %Network_Port%


colordef=C0C0C0
gui, color, %colordef%
gui:
stringmid, clientname, clientname, 0, 12
Gui, Add, Edit, x6 y5 w260 h140 readonly vchat, 
Gui, Add, Edit, x6 y155 w300 h20 vSendText, 
Gui, Add, Button, x316 y155 w70 h20 vhide ghide, HIDE
Gui, Add, Edit, x6 y185 w100 h20 limit12 vClientName, %ClientName%
Gui, Add, Edit, x115 y185 w130 h20 limit12 vClientPass password, %ClientPass%
Gui, Add, Button, x335 y185 w50 h20 vsendbutton gSendviaNet, Send
Gui, Add, Button, x255 y185 w70 h20 vconnect gConnection_Init, Connect
Gui, Add, Edit, x276 y5 w110 h140 readonly vuserlistin, 
Gui, Add, Button, x316 y185 w70 h20 vedit gdisconn, Log Off
;Menu, OptionsMenu, Add, &Hide    Ctrl+H, Hide 
;Menu, OptionsMenu, Add, &Configure,Configure
;Menu, FileMenu, Add, E&xit, Exit
;Menu, MyMenuBar, Add, &File, :FileMenu  
;Menu, MyMenuBar, Add, &Options, :OptionsMenu
;Gui, Menu, MyMenuBar
guicontrol, hide, edit
Gui, Show, h218 w394, Client - Username: %ClientName%
WinGet Gui_ID, ID, Client
guicontrol,,chat, Welcome to your Chat Client!`n`nTo set a different port or IP address in which to connect to you can right click the Icon in your System Tray then click "Configure"`nYou can also type /features to read about all the features your Chat Client has!

return

Configure:
if configurex=1
{
gui, 3:color, C0C0C0 
Gui, 3:Add, Edit, x6 y5 w110 h20 vip, %Network_address%
Gui, 3:Add, Text, x119 y8 w60 h20 , IP Address
Gui, 3:Add, Edit, x6 y25 w110 h20 vport, %Network_port%
Gui, 3:Add, Text, x119 y28 w30 h20 , Port
Gui, 3:Add, Button, x26 y55 w110 h20 , Save
Gui, 3:Show, h80 w175, Configure
}
else 
msgbox,,Client,Connection configuration is available only if disconnected!
Return

3buttonsave:
gui, 3:submit, nohide
gui, 3:destroy
Network_Address=%ip%
Network_port=%port%
menu, tray, tip, Currently Set to`nIP: %Network_Address%`nPort: %Network_Port%
iniwrite, %Network_address%,Settings\clientinfo.ini, Info, ip
iniwrite, %Network_port%,Settings\clientinfo.ini, Info, port

return

3GuiClose:
gui, 3:destroy
return

hide:
if hide<>0
{
hide=0
gui,hide
}
else 
{
hide=1
Gui, Show, h218 w394, Client
}
return

check:
if on=0
{
Settimer,check,off
return
}
if on=1
{
ifnotinstring, userlist, %Clientname%
{
Settimer,check,off
Msgbox, 16, Client, Secure Link Could not be established. Please Restart Client
exitapp
}
Settimer,check,off
}

$numpadenter::
ifwinactive, WinSock Chat Client
{
goto, SendviaNet
}
else
send, {NUMPADENTER}
return


$Enter::
ifwinactive, Client
{
goto, SendviaNet
}
else
send, {ENTER}
return

$UP::
ifwinactive, Client,
{
if las=1
{
guicontrol,,sendtext, %lasttype%
ControlSend Edit2, ^{End}, Client
envadd, las, 1
return
}
if las=2
{
guicontrol,,sendtext, %lasttype2%
ControlSend Edit2, ^{End}, Client
envadd, las, 1
return
}
if las=3
{
guicontrol,,sendtext, %lasttype3%
ControlSend Edit2, ^{End}, Client
envadd, las, 1
return
}
if las=4
{
guicontrol,,sendtext, %lasttype4%
ControlSend Edit2, ^{End}, Client
envadd, las, 1
return
}
if las=5
{
guicontrol,,sendtext, %lasttype5%
ControlSend Edit2, ^{End}, Client
return
}
}
else
send, {UP}
return

$DOWN::
ifwinactive, Client,
{
if las=1
{
guicontrol,,sendtext,
return
}
if las=2
{
guicontrol,,sendtext, %lasttype%
ControlSend Edit2, ^{End}, Client
envsub, las, 1
return
}
if las=3
{
guicontrol,,sendtext, %lasttype2%
ControlSend Edit2, ^{End}, Client
envsub, las, 1
return
}
if las=4
{
guicontrol,,sendtext, %lasttype3%
ControlSend Edit2, ^{End}, Client
envsub, las, 1
return
}
if las=5
{
guicontrol,,sendtext, %lasttype4%
ControlSend Edit2, ^{End}, Client
envsub, las, 1
return
}
}
else
send, {DOWN}
return

Connection_Init:
configurex=0
gui, submit, nohide
iniwrite, %ClientName%,Settings\clientinfo.ini, User, name
iniwrite, %ClientPass%,Settings\clientinfo.ini, User, pass
guicontrol, show, edit
ifinstring, Clientname, %A_Space%
{
Msgbox, 16, Client, You cannot use spaces in your name!
return
}
ifinstring, Clientname, *
{
Msgbox, 16, Client, You cannot use asteriks in your name!
return
}
ifinstring, Clientname, RX2
{
Msgbox, 16, Client, You cannot use that in your name!
return
}
ifinstring, Clientname, SR1
{
Msgbox, 16, Client, You cannot use that in your name!
return
}
ifinstring, Clientname, :
{
Msgbox, 16, Client, You cannot use colons in your name!
return
}
ifinstring, Clientname, $
{
Msgbox, 16, Client, $ is reserved for ChatServer Prefix.`n %A_Space%  %A_Space% %A_Space% %A_Space%%A_Space% %A_Space%You may not use it!
return
}
if Clientname=Console
{
Msgbox, 16, Client,
(
%A_Space%%A_Space%%A_Space%%A_Space%Please choose a nickname to use while chatting in this server.
             You are limited to 12 characters in your nickname.
You will be prevented from using certain characters in your nickname.
)
return
}
ifinstring, ClientPass, %A_Space%
{
Msgbox, 16, Client, You cannot use spaces in your pass!
return
}
ifinstring, ClientPass, *
{
Msgbox, 16, Client, You cannot use asteriks in your pass!
return
}
ifinstring, ClientPass, RX2
{
Msgbox, 16, Client, You cannot use that in your pass!
return
}
ifinstring, ClientPass, SR1
{
Msgbox, 16, Client, You cannot use that in your pass!
return
}
ifinstring, ClientPass, :
{
Msgbox, 16, Client, You cannot use colons in your pass!
return
}
ifinstring, ClientPass, $
{
Msgbox, 16, Client, $ is reserved for ChatServer Prefix.`n %A_Space%  %A_Space% %A_Space% %A_Space%%A_Space% %A_Space%You may not use it!
return
}
if ClientPass=Console
{
Msgbox, 16, Client,
(
%A_Space%%A_Space%%A_Space%%A_Space%Please choose a nickpass to use while chatting in this server.
             You are limited to 12 characters in your nickpass.
You will be prevented from using certain characters in your nickpass.
)
return
}
;menu, tray, delete, Configure
guicontrol,,chat,
guicontrol, enable, edit
;guicontrol, disable, edit
guicontrol,hide, connect
guicontrol, hide, clientname
guicontrol, hide, clientpass
guicontrol, move, sendbutton, x6 y185 w300 h20
OnExit, ExitSub 




socket := ConnectToAddress(Network_Address, Network_Port)
if socket = -1 
{

msgbox Error connecting to server! This program will now exit!
    ExitApp
	}

Process, Exist  
DetectHiddenWindows On
ScriptMainWindowId := WinExist("ahk_class AutoHotkey ahk_pid " . ErrorLevel)
DetectHiddenWindows Off


NotificationMsg = 0x5555  ; An arbitrary message number, but should be greater than 0x1000.
OnMessage(NotificationMsg, "ReceiveData")

menu, tray, tip, Currently connected to`nIP: %Network_Address%`nPort: %Network_Port%

FD_READ = 1     ; Received when data is available to be read.
FD_CLOSE = 32   ; Received when connection has been closed.
if DllCall("Ws2_32\WSAAsyncSelect", "UInt", socket, "UInt", ScriptMainWindowId, "UInt", NotificationMsg, "Int", FD_READ|FD_CLOSE)
{
    MsgBox % "WSAAsyncSelect() indicated Winsock error " . DllCall("Ws2_32\WSAGetLastError")
    ExitApp
}
sendtext=%ClientName%@%ClientPass% DOLOGIN1
gosub send1
return

SendviaNet:
Gui, Submit, NoHide
lasttype5=%lasttype4%
lasttype4=%lasttype3%
lasttype3=%lasttype2%
lasttype2=%lasttype%
lasttype=%sendtext%
stringgetpos, count2, sendtext, /, L
if count2=0
{
if sendtext=/features
{
if con=1
{
tooltip, That command is only available when not connected!, 220, 180
guicontrol,,sendtext,
Settimer, removetooltip, 4000
return
}
if con=0
{
guicontrol,,sendtext,
Guicontrol,,Chat,
(
Chat Client Features List:

Winsock chat communication
Connected and Disconnected messages
User List
Kick users (server only)
IP grabber (server only)
Command mode
 - Ping
 - IP2Location
 - VisitWeb
Configure Connection Menu
Hit 'Enter' = Quick Send
Hit 'UP' = Show Last Sent (Up to 5)
Hit 'DOWN' = Scroll Down on Last Sent (Clear if on last sent)
)
return
}
}

if Sendtext=/cmd
{
if con=1
{
tooltip, Command mode only available when not connected!, 220, 180
guicontrol,,sendtext,
Settimer, removetooltip, 4000
return
}
if con=0
guicontrol,,sendtext,
guicontrol,,chat, Command Mode Enabled!`n`n          Available commands are as follows`nPing - /cmd ping (ip/hostname)`nIP2Location - /cmd i2l (ip)`nVisitWeb - /cmd vw (url)`n`nCommand Usage:`nPing Command- Type in the syntax and fill in the "(ip/hostname)" with an IP or hostname.`nIP2Location Command- Type in the syntax and fill in the "(ip)" with an IP you want located. The script will require Internet access to check with the Whois website.`nYou can also leave the "(ip)" blank, and it will display your current location.`nVisitWeb Command- Write out the syntax and fill in the (url) for a URL you wish to go to.`n/info Informations about server and client
return
}


ifinstring, sendtext, /reg
{
if con=1
   {
   Gui,Submit,NoHide
   guicontrol,,sendtext,
   ;msgbox %sendtext%
;
      if sendtext=/reg
   guicontrol,,chat, Command usage:`n /reg username@pass
   else
   gosub send1
   return
   }
}
;if Sendtext=/sendfile
;{
;gosub sendfile
;return
;}

ifinstring, sendtext, /w 
{
if con=1
   {
   ifinstring, sendtext, /w %ClientName%
   {
    guicontrol,,sendtext,
   guicontrol,,chat, Command usage:`n /w username`n YOU CAN NOT PM YOURSELF DUMBASS!
   }
   else
   {
   Gui,Submit,NoHide
   
   guicontrol,,sendtext,
   StringSplit, wisp,sendtext,%A_space%
      if sendtext=/w
   guicontrol,,chat, Command usage:`n /w username
   else
   {
   sendtext=/w %ClientName%@%wisp2%@Requested PM
   SendData(socket,sendtext)
   sendtext=
   }
   return
   }
   return
   }
}

if Sendtext=/info
{
if con=1
   {
   Gui,Submit,NoHide
   guicontrol,,sendtext,
   hfe=%userlist%
   stringreplace, hfe, hfe, |,`n,ALL
guicontrol,,chat, Currently connected to`nIP: %Network_Address%`nPort: %Network_Port%`nwith nick name: %Clientname%`nYour IP: %A_IPAddress1%`n_______________________________`n`nUsers Online: `n %hfe%_______________________________
return
   }
if con=0
   {
   Gui,Submit,NoHide
   guicontrol,,sendtext,
   guicontrol,,chat, Current server info`nIP: %Network_Address%`nPort: %Network_Port%`nConnecting with nick name: %Clientname% `nYour IP: %A_IPAddress1%`n_______________________________
return
   }
}
ifinstring, sendtext, /cmd ping
{
if con=1
   {
tooltip, Command mode only available when not connected!, 220, 180
guicontrol,,sendtext,
Settimer, removetooltip, 4000
return
   }
if con=0
   {
ping=%sendtext%
guicontrol,,sendtext,
guicontrol,,chat, Starting ping now`nPlease wait for results...
stringreplace, ping2, ping, /cmd,
stringreplace, ping3, ping2, ping,
stringreplace, ping4, ping3, %A_space%,
filedelete,Settings\pinger.bat
filedelete,Settings\Pinglog.txt
detecthiddenwindows, on
loop,
{
Process, close, cmd.exe
Process, exist, cmd.exe 
if errorlevel=0
break
}
fileappend,
(
cd\
ping -n 3 %ping4% >> "Settings\Pinglog.txt"
),Settings\pinger.bat
run, pinger.bat,Settings\, hide useerrorlevel, 
if errorlevel=ERROR
{
guicontrol,,chat, Could not run ping execution file!
return
}
loop,
{
Process, exist, cmd.exe, 
if errorlevel=0
break
}
detecthiddenwindows, off
fileread, outping,Settings\Pinglog.txt
guicontrol,, chat, %outping%
ControlSend Edit1, ^{End}, Client
filedelete,Settings\pinger.bat
filedelete,Settings\Pinglog.txt
return
   }
}
ifinstring, sendtext, /cmd i2l
{
if con=1
   {
tooltip, Command mode only available when not connected!, 220, 180
guicontrol,,sendtext,
Settimer, removetooltip, 4000
return
   }
if con=0
{
i2l=%sendtext%
guicontrol,,sendtext,
guicontrol,,chat,Starting IP2Location Function`nPlease wait for results...
stringreplace, i2l2, i2l, /cmd,
stringreplace, i2l3, i2l2, i2l,
stringreplace, i2l4, i2l3, %A_space%,
;stringtrimleft, i2l4, i2l4, 1
filedelete,Settings\1.txt
stringreplace, ip2, i2l4, -, ., All
ip=%ip2%
urldownloadtofile, http://www.dnsstuff.com/tools/whois.ch?ip=%ip%,Settings\1.txt
fileread, 1,Settings\1.txt
StringGetPos, 2, 1, Location:
stringmid, 3, 1, %2%,
stringreplace, 4, 3, ], `n, All
filedelete,Settings\2.txt
fileappend, %4%,Settings\2.txt
filereadline, 5,Settings\2.txt, 2
bl=
stringreplace, 6, 5, Location:, %bl%, All
filedelete,Settings\2.txt
filedelete,Settings\1.txt

if 6=<html xmlns="http://www.w3.org/1999/xhtml">
{
guicontrol,,chat, Could not locate IP!
return
}
if ip=
{
ip=%A_Ipaddress1%
}
fileappend, %ip% found at%6%]`n,Settings\i2l.txt
fileread, i2lout,Settings\i2l.txt
guicontrol,,chat, %i2lout%
return
}
}
ifinstring, sendtext, /cmd vw
{
if con=1
   {
tooltip, Command mode only available when not connected!, 220, 180
guicontrol,,sendtext,
Settimer, removetooltip, 4000
return
   }
if con=0
{
vw=%sendtext%
guicontrol,,sendtext,
guicontrol,,chat,Visiting address now...
stringreplace, vw2, vw, /cmd,
stringreplace, vw3, vw2, vw,
stringreplace, vw4, vw3, %A_space%,
stringtrimleft, vw4, vw4, 1
run, %vw4%,, useerrorlevel
if ERRORlevel=ERROR
{
Guicontrol,,chat,Error when visiting address (%vw4%)`nThis is sometimes caused with having Firefox as your default browser`nIf this is the case, ignore this error, and firefox will open normally.
return
}
Guicontrol,,chat,Address Visited!
return
}
}
}
if Sendtext=
{
return
}
if Sendtext=%A_Space%
{
tooltip, You cannot send blank lines!, 220, 180
guicontrol,,sendtext,
Settimer, removetooltip, 4000
return
}
if Sendtext=%A_Space%%A_Space%
{
tooltip, You cannot send blank lines!, 220, 180
guicontrol,,sendtext,
Settimer, removetooltip, 4000
return
}
ifinstring, Sendtext, %A_Space%%A_Space%%A_Space%
{
tooltip, Too many consecutive spaces!, 220, 180
guicontrol,,sendtext,
Settimer, removetooltip, 4000
return
}
ifinstring, SendText, RX2CLIENTCON:
{
tooltip, You cannot send that text!, 220, 180
guicontrol,,sendtext,
Settimer, removetooltip, 4000
return
}
ifinstring, sendtext, DOLOGIN1
{
tooltip, You cannot send that text!, 220, 180
guicontrol,,sendtext,
Settimer, removetooltip, 4000
return
}

SendText =%ClientName%: %SendText%

guicontrol,,SendText,

send1:
SendData(socket,SendText)
SendText =
return

RemoveToolTip:
SetTimer, RemoveToolTip, Off
ToolTip
return

ConnectToAddress(IPAddress, Port)
{
    VarSetCapacity(wsaData, 32)  
    result := DllCall("Ws2_32\WSAStartup", "UShort", 0x0002, "UInt", &wsaData) 
    if ErrorLevel
    {
        MsgBox WSAStartup() could not be called due to error %ErrorLevel%. Winsock 2.0 or higher is required.
        return -1
    }
    if result  
    {
        MsgBox % "WSAStartup() indicated Winsock error " . DllCall("Ws2_32\WSAGetLastError")
        return -1
    }


    AF_INET = 2
    SOCK_STREAM = 1
    IPPROTO_TCP = 6
    socket := DllCall("Ws2_32\socket", "Int", AF_INET, "Int", SOCK_STREAM, "Int", IPPROTO_TCP)
    if socket = -1
    {
        MsgBox % "socket() indicated Winsock error " . DllCall("Ws2_32\WSAGetLastError")
        return -1
    }

   
    SizeOfSocketAddress = 16
    VarSetCapacity(SocketAddress, SizeOfSocketAddress)
    InsertInteger(2, SocketAddress, 0, AF_INET)  
    InsertInteger(DllCall("Ws2_32\htons", "UShort", Port), SocketAddress, 2, 2)   
    InsertInteger(DllCall("Ws2_32\inet_addr", "Str", IPAddress), SocketAddress, 4, 4)   

   
    if DllCall("Ws2_32\connect", "UInt", socket, "UInt", &SocketAddress, "Int", SizeOfSocketAddress)
    {
        MsgBox % "connect() indicated Winsock error " . DllCall("Ws2_32\WSAGetLastError") . "?"
        return -1
    }
    return socket  
}


ReceiveData(wParam, lParam) 
{
Critical
   global ShowRecieved, pmchat , pmedit
    socket := wParam
    ReceivedDataSize = 4096  
    Loop 
    {
        VarSetCapacity(ReceivedData, ReceivedDataSize, 0)  
        ReceivedDataLength := DllCall("Ws2_32\recv", "UInt", socket, "Str", ReceivedData, "Int", ReceivedDataSize, "Int", 0)
        if ReceivedDataLength = 0   
            ExitApp  
        if ReceivedDataLength = -1
        {
            WinsockError := DllCall("Ws2_32\WSAGetLastError")
            if WinsockError = 10035  
                return 1
            if WinsockError <> 10054 
             
              MsgBox % "recv() indicated Winsock error " . WinsockError
            ExitApp  
        }
   logos=0
        Loop, parse, ReceivedData, `n, `r
        {

gui, submit, nohide
            ShowRecieved = %ShowRecieved%%A_LoopField%  
settimer, check, 2500
   ifnotinstring, Showrecieved, connected
   {
ifnotinstring, Showrecieved, :
   {
   gosub, adddellist

   }
if ShowRecieved= RX2CLIENTCON:
   {
   gosub, connectpend
   gosub, turnon
   sleep, 250
   con=1
   logos=0
   return
   }
   /*
if ShowRecieved= SR1NONUSER:
   {
   if con = 1
   {
Msgbox, 48, Info, Server returned: Not A Valid User Or Incorect Password!
gosub disconn
}
   return
   }
 */  
ifinstring , Showrecieved, LOGO
{
;logo:=Dec_Hex(logo)
ifnotexist , Settings\client.logo
{
Stringreplace, logo, Showrecieved, LOGO
logo:=Dec_Hex(logo)
filedelete , Settings\client.txt
fileappend, %logo%`n,Settings\client.logo
fileappend, %logo%`n, Settings\client.txt
 fileread, chat1,Settings\client.logo
   guicontrol,,chat, %chat1%
    ShowRecieved = 
		    return 1
;msgbox logo
;Guicontrol,,chat,logo
;Showrecieved=
} 
Showrecieved=
return 1
}

}

if ShowRecieved <>
{
;msgbox %ShowRecieved%
 fileappend, %ShowRecieved%`n, Settings\client.txt
   fileread, chat1, Settings\client.txt
   guicontrol,,chat, %chat1%
    ShowRecieved = 
        ControlSend Edit1, ^{End}, Client
   ifwinnotactive, Client
   {
   Soundplay, %a_windir%\Media\chimes.wav
   }
   }
        }
    }
    return 1  
}


SendData(wParam,SendData)
{
socket := wParam
SendDataSize := VarSetCapacity(SendData)
SendDataSize += 1
sendret := DllCall("Ws2_32\send", "UInt", socket, "Str", SendData, "Int", SendDatasize, "Int", 0)
;send( sockConnected,> welcome, strlen(welcome) + 1, NULL);
}

turnon:
on=1
return

adddellist:
ShowRecieved2=%ShowRecieved%
ifinstring, Showrecieved2, RX2KICKPLAYER
{
stringreplace, Showrecieved2, Showrecieved2, RX2KICKPLAYER,-,All
if Showrecieved2=-%clientname%
   {
gosub, kickexit
   }
Showrecieved=
exit
}
ifinstring, ShowRecieved2, connected!
{
showrecieved2=
return
}
ifinstring, ShowRecieved2,%clientname%%a_space%notvaliduserorpass
{
showrecieved2=
Msgbox, 48, Info, Server returned: Not A Valid User Or Incorect Password!
exitapp
}
   ifinstring, ShowRecieved,notvaliduserorpass!
{
showrecieved=
return
}

ifinstring, Showrecieved2, /w 
{
ifinstring, Showrecieved2, @%ClientName%@
   {
   ;msgbox pm
   gosub wispermenu
   Stringreplace, rcvtxt, Showrecieved2, /w%a_space%
   StringSplit, wisp4me,rcvtxt,@
   if wisp4me3<>
   {
   fileappend, %wisp4me1%: %wisp4me3%`n, Settings\pmchat.txt
   fileread, wispmsg, Settings\pmchat.txt
   guicontrol,55:,pmchat,%wispmsg%
   }

   }
        ShowRecieved=
	 Showrecieved2=
   return
   }


ifinstring, Showrecieved2, SR1CLIENTADDLIST
{
filedelete, Settings\userlistc.txt
stringreplace, ShowRecieved2, ShowRecieved2, SR1CLIENTADDLIST,,ALL
stringreplace, ShowRecieved2, ShowRecieved2, *,`n, All
fileappend, %ShowRecieved2%, Settings\userlistc.txt
fileread,  userlist, Settings\userlistc.txt
;stringreplace, userlist2, userlist, *, `n, ALL
guicontrol,,userlistin, %userlist%
userlist2=%userlist%
stringreplace, userlist2, userlist2, %clientname%, %A_Space%
fileappend, %userlist2%, Settings\usernamestemp.txt
if checkornot=0
{
Loop, read,Settings\usernamestemp.txt
{
    last_line := A_LoopReadLine
if last_line=%clientname%
{
guicontrol,,userlistin,
sleep, 500
nam=1
exitapp
} 
}
checkornot=1
}
filedelete,Settings\usernamestemp.txt
ShowRecieved=
ShowRecieved2=
exit
}
ShowRecieved2=
return

connectpend:
ShowRecieved=
if con=0
{
SendText=%Clientname% connected!
gosub, Send1
con=1
return
}
else
return

InsertInteger(pInteger, ByRef pDest, pOffset = 0, pSize = 4)

{
    Loop %pSize%  
        DllCall("RtlFillMemory", "UInt", &pDest + pOffset + A_Index-1, "UInt", 1, "UChar", pInteger >> 8*(A_Index-1) & 0xFF)
}



ExitSub:  

if nam=1
{
sleep, 500
}
open= %Clientname% disconnected!
SendData(socket,open)
sleep, 250
gui, destroy
sleep, 250
DllCall("Ws2_32\WSACleanup")
;sleep, 2000
filedelete,Settings\userlistc.txt
filedelete,Settings\client.txt
filedelete,Settings\i2l.txt
filedelete,Settings\usernamestemp.txt
filedelete,Settings\pmchat.txt
filedelete , Settings\client.logo
if nam=1
{
Msgbox, 16, Client, Client name already in use!
exitapp
}
ExitApp

Kickexit:
gui, destroy
open= %Clientname% was kicked!
SendData(socket,open)
sleep, 500
DllCall("Ws2_32\WSACleanup")
Msgbox, 16, Client, You were kicked from the Server!
filedelete , Settings\client.logo
filedelete ,Settings\pmchat.txt
exitapp

disconn:
chat=
open= %Clientname% disconnected!
SendData(socket,open)
sleep, 250
;gui, destroy
sleep, 250
DllCall("Ws2_32\WSACleanup")
filedelete,Settings\i2l.txt
filedelete,Settings\usernamestemp.txt
on=0
checkornot=0
con=0
end=0
las=1
ifexist,Settings\clientinfo.ini
{
iniread, Network_address,Settings\clientinfo.ini, Info, ip
iniread, Network_port,Settings\clientinfo.ini, Info, port
}
menu, tray, tip, Currently Set to`nIP: %Network_Address%`nPort: %Network_Port%

Guicontrol,,Chat,
(
Chat Client Features List:

Winsock chat communication
Connected and Disconnected messages
User List
Kick users (server only)
IP grabber (server only)
Command mode
 - Ping
 - IP2Location
 - VisitWeb
Configure Connection Menu
Hit 'Enter' = Quick Send
Hit 'UP' = Show Last Sent (Up to 5)
Hit 'DOWN' = Scroll Down on Last Sent (Clear if on last sent)
)
guicontrol, hide, edit
guicontrol,show, connect
guicontrol, show, clientname
guicontrol, show, clientpass
guicontrol, move, sendbutton,  x335 y185 w50 h20
configurex=1
filedelete,Settings\userlistc.txt
filedelete,Settings\client.txt
filedelete,Settings\i2l.txt
filedelete,Settings\usernamestemp.txt
filedelete,Settings\pmchat.txt
filedelete , Settings\client.logo
guicontrol,,userlistin, 
return

Guiclose:
filedelete,Settings\userlistc.txt
filedelete,Settings\client.txt
filedelete,Settings\i2l.txt
filedelete,Settings\usernamestemp.txt
filedelete , Settings\client.logo
gosub, exitsub

FileReadEx( ByRef V,F,B,O ) {
return varsetcapacity(v,b,0)-o+(h:=dllcall("_lopen",str,f,int,0))-h+dllcall("_llseek",uint
 ,h,uint,o,int,0)-dllcall("_lread",uint,h,str,v,int,b)+dllcall("_lclose",uint,h) ? -1 : &v     
}

sendfile(file,chunksize=10000)
{
FileGetSize, size, %file%
chunk:=size/chunksize
chunks:=Round(chunk)
StringSplit, final, chunk, .
lastsize:=size-chunks
finalbytes:=lastsize*chunksize
offset=0

lastoffset:=chunks*chunksize
loop, %chunks%
{
FileReadEx( Bin, file, chunksize,offset )   
offset:=%offset%+%chunksize%
SendData(socket,Bin)
Bins=%Bins%%Bin%
}
;msgbox %size%`n%lastsize%`n%finalbytes%`n%lastoffset%
FileReadEx( Bin, file, finalbytes,lastoffset ) 
SendData(socket,Bin)
Bins=%Bins%%Bin%
Guicontrol,,Chat,%Bins%
}

sendfile:
FileSelectFile, file , Options, , Select the file to send, *.*
;sendfile(file,10000)
sendfile(file)
return

wispermenu:
if isgui<>1
{
gui,55: color, %colordef%
Gui ,55:  Add, Edit, x6 y7 w380 h140 readonly vpmchat, 
Gui,55:  Add, Edit, x6 y157 w300 h20 vpmedit, 
Gui,55:  Add, Button, x326 y187 w50 h20 gmeclose, Exit
Gui,55: Add, Button, x6 y187 w300 h20 gsendpm, Send
Gui,55: Show, x440 y376 h218 w394, Private Message
isgui=1
}
Return

55guiclose:
isgui=0
gui, 55: destroy
filedelete,Settings\pmchat.txt
return

exit:
if con=0
{
exitapp
}
if con=1
{
goto, exitsub
}

meclose:
return

sendpm:
Gui,55: Submit,NoHide
guicontrol,55:,pmedit,
pm=/w %ClientName%@%wisp4me1%@%pmedit%
SendData(socket,pm)
fileappend, %ClientName%: %pmedit%`n, Settings\pmchat.txt
fileread, wispmsg, Settings\pmchat.txt
guicontrol,55:,pmchat,%wispmsg%
return


Enc_Hex(x) ;originally: String2Hex(x) ; Convert a string to hex digits (modified to accommodate new line chars)
{
   prevFmt = %A_FormatInteger%
   SetFormat Integer, H ; this function requires hex format
   Loop Parse, x
      hex .= 0x100+Asc(A_LoopField)
   StringReplace hex, hex, 0x1,,All
   SetFormat Integer, %prevFmt% ; restore original integer formatting
   Return hex
}

Dec_Hex(x) ;originally: Hex2String(x) ; Convert a huge hex number to string (modified to suit String2Hex above)
{
   Loop % StrLen(x)/2
   {
      Pos:=(A_Index-1)*2+1
      StringMid hex, x, Pos, 2
      string := string . Chr("0x" hex)
   }
   Return string
}
@maestrith perhaps your IRC could be used here?
Last edited by labrint on 04 Apr 2022, 02:04, edited 3 times in total.
User avatar
Chunjee
Posts: 1499
Joined: 18 Apr 2014, 19:05
Contact:

Re: 2 Way chat - Realtime communication between 2 AHK scripts

04 Apr 2022, 01:41

The way you are verifying the doctor has the available medicine is... checking his gui listbox...

I think you need a real database or something more machine readable than the doctor's gui interface.
User avatar
labrint
Posts: 383
Joined: 14 Jun 2017, 05:06
Location: Malta

Re: 2 Way chat - Realtime communication between 2 AHK scripts

04 Apr 2022, 01:45

Chunjee wrote:
04 Apr 2022, 01:41
The way you are verifying the doctor has the available medicine is... checking his gui listbox...

I think you need a real database or something more machine readable than the doctor's gui interface.
The thing is I need to check one list box at a time, not multiple. The doctor's script must wait for confirmation of a single list box, not confirming multiple list boxes at a time.
User avatar
labrint
Posts: 383
Joined: 14 Jun 2017, 05:06
Location: Malta

Re: 2 Way Realtime communication between 2 AHK scripts [IRC/WebSocket/WinSock]

04 Apr 2022, 06:05

For those wanting a quick chat ahk script:

Code: Select all

Gui Add, ActiveX, vdoc xm w1000 h300, about:<!DOCTYPE html><meta http-equiv="X-UA-Compatible" content="IE=edge"> ; the "IE=edge" should force Shell.Explorer to use the latest IE renderer. I have internet explorer 11 and Microsoft Edge installed.
doc.silent := true ; Surpress JS Error boxes, commented out for debugging
doc.Navigate("https://stin.to/k85d4")


Gui, Show
Return

Return to “Ask for Help (v1)”

Who is online

Users browsing this forum: oktavimark and 361 guests