AutoHotkey Homepage AutoHotkey Community
Let's help each other out
 
 FAQFAQ   SearchSearch   MemberlistMemberlist   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

TCP/IP Server+Client Chat Script (w/ Features)
Goto page Previous  1, 2, 3, 4, 5, 6, 7, 8, 9  Next
 
Reply to topic    AutoHotkey Community Forum Index -> Scripts & Functions
View previous topic :: View next topic  

Would you use this script?
Yes
72%
 72%  [ 24 ]
No
9%
 9%  [ 3 ]
Frequently
9%
 9%  [ 3 ]
Maybe once or Twice
9%
 9%  [ 3 ]
Total Votes : 33

Author Message
Guest






PostPosted: Sun Feb 21, 2010 9:17 pm    Post subject: Reply with quote

Have you already checked to make sure no firewall hardware or software is blocking traffic. Also make sure the port is identical on both. There are some things I can't figure out about this script and I wonder if it has bugs, but I can attest that it certainly connects.
Back to top
WankaUSR



Joined: 14 Aug 2007
Posts: 86

PostPosted: Mon Feb 22, 2010 8:26 am    Post subject: Reply with quote

check to see if you router ( I guess you use a router since the IP class is 192.168.*) blocks traffic betwen computer. Mine blocks ping and specific ports so please check that
Back to top
View user's profile Send private message Visit poster's website
WankaUSR



Joined: 14 Aug 2007
Posts: 86

PostPosted: Mon Feb 22, 2010 12:13 pm    Post subject: Reply with quote

WankaUSR mod version 0.4
This is based on jmanx latest version found on page one and added all my functions plus others.
Features added (WankaUSR MOD):
-Server logo (text only). It can be modified after compilation in EditLogo traymenu
-User can register (logging in with user anonimus shows register window).Registration is based on an random id (numbers and letters) generated on client start up. Stored password are encrypted in server
-Server has the option to allow/deny anonimus users from registering
-Maximum number of registered users can be set in server
-Kill server option without exiting the application (force disconnect al users)

Server commands:
/reg off ( on ) - allow anonimus users to register or not
/maxusers #number of users# ex: /maxusers 10000 - number of users that can register
/edituser username newpass is user does not exist it will be created
/info Server commands

To do:
-Client2client filesend
-Skin for the gui and buttons
-More server/client commands( just suggest something and if it possible I will do it)
Please post any bugs because it wasn't heavily tested also there is a lot of leftover code from testing (sorry about that)
Client:
Code:

;#singleinstance force
#singleinstance off
#Persistent
#MaxMem 256
;#notrayicon
ifnotexist,Settings
{
Filecreatedir,Settings
}
randomvar:=randomid("10")
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

randomid:=randomid()
on=0
checkornot=0
con=0
end=0
las=1
encryptpass=averylongandhardtocrackpass
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
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, Clientname,Anonimus
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

DllCall("Ws2_32\WSACleanup")


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
}
ClientPass:=Encode(ClientPass, encryptpass) ;use your own encryption password. The sever password must be the same
if ClientName=Anonimus
      ClientName:= "Anonimus" . randomid
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
   }
}

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
}
}
}

sendtext2=%sendtext%
stringmid, sendtext2, sendtext2, 0, 4
if sendtext2=/msg
{
guicontrol,,SendText,
stringtrimleft, cmd2, sendtext, 5
stringreplace, cmd2, cmd2, %A_space%,`n
filedelete, Settings\tempcheckc.txt
fileappend, %cmd2%, Settings\tempcheckc.txt
filereadline, nameinc, Settings\tempcheckc.txt, 1
if nameinc=%Clientname%
{
tooltip, You cannot send a message to yourself!, 220, 180
Settimer, removetooltip, 4000
filedelete, Settings\tempcheckc.txt
return
}
filereadline, msginc, Settings\tempcheckc.txt, 2
ifinstring, msginc, *
{
tooltip, Please do not use asteriks in your message!, 220, 180
filedelete, Settings\tempcheckc.txt
return
}

msginc2=509SENDPM*%Clientname%*%nameinc%*%msginc%
filedelete, Settings\tempcheckc.txt
loop, read, Settings\userlistc.txt
{
currentline := A_Loopreadline
if nameinc=%currentline%
{
 SendData(socket,msginc2)
fileappend, [Private] (To: %nameinc%) %msginc% `n, Settings\client.txt
   fileread, chat1, Settings\client.txt
   guicontrol,,chat, %chat1%
           ControlSend Edit1, ^{End}, WinSock Chat Client

return
}
if nameinc=$
{

 SendData(socket,msginc2)
fileappend, [Private] (To: $ChatServer) %msginc% `n, Settings\client.txt
   fileread, chat1, Settings\client.txt
   guicontrol,,chat, %chat1%
           ControlSend Edit1, ^{End}, WinSock Chat Client

return
}
}
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,myusrname , mypass , mypass2, randomid
    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
if ShowRecieved=USRREG%randomid%
{
guicontrol, disable, sendtext
guicontrol, disable, sendbutton
settimer, check, off
gosub regnewuser
Showrecieved2=
Showrecieved=
   return
   }
ifinstring , Showrecieved, USRREG
      return
if ShowRecieved=NOUSRREG
{
settimer, check, off
guicontrol, disable, sendtext
guicontrol, disable, sendbutton
Msgbox, 48, Info, Server returned: Registrations are now closed and Anonimus user has been disabled!
Showrecieved2=
Showrecieved=
gosub, exitsub
   }
   
ifnotinstring , Showrecieved, connected
   {
ifnotinstring, Showrecieved, :
   {
   gosub, adddellist

   }
if ShowRecieved= RX2CLIENTCON:
   {
   gosub, connectpend
   gosub, turnon
   sleep, 250
   con=1
   logos=0
   return
   }
   
ifinstring , Showrecieved, 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
}
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=
settimer, check, off
guicontrol, disable, sendtext
guicontrol, disable, sendbutton
Msgbox, 48, Info, Server returned: Not A Valid User Or Incorect Password!
exitapp
}
   ifinstring, ShowRecieved,notvaliduserorpass!
{
showrecieved=
return
}

ifinstring, ShowRecieved2, %myusrname%%a_space%is%a_space%now%a_space%a%a_space%registered%a_space%user
{
iniwrite, %myusrname%,Settings\clientinfo.ini, User, name
iniwrite, %mypasspure%,Settings\clientinfo.ini, User, pass
reload
}

ifinstring, ShowRecieved2, %myusrname%%a_space%is%a_space%already%a_space%a%a_space%registered%a_space%user
{
showrecieved2=
showrecieved=
settimer, check, off
Msgbox, 48, Info, Server returned: User name already registered!
gosub regnewuser
return
}

ifinstring, ShowRecieved2,505NOSTANDARDLOGIN
{
showrecieved2=
showrecieved=
settimer, check, off
Msgbox, 48, Info 505, Server returned: You can not use preset username to register!`n"Username" user is restricted to acces server!
gosub regnewuser
return
}

ifinstring, ShowRecieved2,USRMAXREG
{
showrecieved2=
showrecieved=
settimer, check, off
Msgbox, 48, Info, Server returned: Maximum number of registered user have been achieved!`nRegistration to server is denied!
reload
}

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
{
firsthit=0
Loop, read,Settings\usernamestemp.txt
{
    last_line := A_LoopReadLine
   if %ClientName%<>Anonimus
   {
if last_line=%clientname%
{
if firsthit=0
{
firsthit=1
continue
}
guicontrol,,userlistin,
sleep, 500
nam=1
filedelete, Settings\usernamestemp.txt
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
guicontrol,,userlistin,
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

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

regnewuser:
Random, gui_rand, 10, 100
gui,%gui_rand%: color, %colordef%
Gui,%gui_rand%: Add, Edit, x16 y37 w280 h20 vmyusrname, Username
Gui,%gui_rand%: Add, Edit, x16 y97 w280 h20 password vmypass, password
Gui,%gui_rand%: Add, Edit, x16 y157 w280 h20 password vmypass2, password
Gui,%gui_rand%: Add, Text, x16 y7 , Username:
Gui,%gui_rand%: Add, Text, x16 y67 , Password:
Gui,%gui_rand%: Add, Text, x16 y127 , Confirm password
Gui,%gui_rand%: Add, Button, x16 y187 w130 h30 gregmenow, Register
Gui,%gui_rand%: Add, Button, x156 y187 w140 h30 gcancelreg, Cancel
Gui,%gui_rand%: Show,h227 w312, Registration Box ID: %randomid%
Return

cancelreg:
reload

regmenow:
gui,%gui_rand%:Submit,NoHide
gui, %gui_rand%: destroy
if mypass=%mypass2%
{
ClientName=%myusrname%
mypasspure=%mypass%
mypass:=Encode(mypass, encryptpass) ;use your own encryption password. The sever password must be the same is you want to be able to modify user from the server side
data=/reg %myusrname%@%mypass%
SendData(socket,data)
}
else
{
msgbox Passwords  did not match!
gosub regnewuser
}
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)
}

Encode(Text, Key)
 {
  cKey := Key                                 ;Create copy of "Key"
  if % StrLen(Key) < StrLen(Text)             ;Need "Key" length to be same as or bigger than "Text"
   Loop
    {
     cKey .= Key                              ;Key * 2
     if % StrLen(cKey) >= StrLen(Text)
      break
    }
 
  Loop % StrLen(Text)
   {
    StringMid, t_%A_Index%, Text, %A_Index%, 1         ;Get ASCII value of Text, and ASCII value of Key
    StringMid, k_%A_Index%, cKey, %A_Index%, 1         ;then begin to add the values individially ex//
    cText.= Chr(Asc(k_%A_Index%) + Asc(t_%A_Index%))   ;Key = ab, Text = cd. Get ASCII value of a, then
   }                                                   ;add it to ASCII value of c, get ASCII value of
  return cText                                         ;b and add to ASCII value of d
 }
 
  randomid(lenght="10")
 {
 loop,%lenght%
   {
      Random, nr_rand, 0, 9
      ;Random, char_rand, 97, 122 ;all lowercase a-z
      Random, char_rand, 97, 102 ;all lowercase a-f
      char := chr(char_rand)
      randomid .= char . nr_rand
   }

 return, randomid
 }

Server:
Code:

#singleinstance force
#Persistent

logedin=0
logo=
(
~~~~~Welcome to Winsock-Chat!~~~~~
Main code by jmanx mod by wankausr
http://www.autohotkey.com/forum/viewtopic.php?t=32455
)
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
iniwrite, 1,Settings\users.ini, userSetting,allowAnoniumsReg
iniwrite, 100,Settings\users.ini, userSetting,allowMaxUsers
}
iniread, anonimuson,Settings\users.ini, userSetting, allowAnoniumsReg
iniread, usrsmax,Settings\users.ini, userSetting, allowMaxUsers
Network_Address = 0.0.0.0
Network_Port = 1000
encryptpass=averylongandhardtocrackpass
badstrings=USRREG|USRMAXREG|NOUSRREG|505NOSTANDARDLOGIN
if anonimuson=1
annon=ON
else
annon=OFF

reged:=userreged()
mainchattxt=
(
~~~~~Welcome to Winsock-Chat Sever!~~~~~
Main configuration informations:
Allow annonimus users to register :  %annon%
Maximum number of possible registrations:  %usrsmax%
Connection port: %Network_Port%
Registered users (including Anonimus) : %reged%
Command usage:
/reg off ( on ) - allow anonimus users to register or not
/maxusers #number of users#  ex: /maxusers 10000  -  number of users that can register
/edituser username newpass is user does not exist it will be created
/info This message
---------------------------------------------------------------------------------------------------------------
)
fileappend, %mainchattxt%`n,Settings\server.txt
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, %mainchattxt%
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
Gui, Show, x135 y95 h233 w501, WinSock Chat Server
WinGet Gui_ID, ID, WinSock Chat Server
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

$numpadenter::
ifwinactive, WinSock Chat Server
{
goto, SendviaNet
}
else
send, {NUMPADENTER}
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
      Sendtext=
    }
    sleep 500
}   
return

SendviaNet:
Gui, Submit, NoHide

stringmid, cmd2, sendtext, 0, 4
if cmd2=/msg
{
guicontrol,,SendText,

stringtrimleft, cmd2, sendtext, 5
stringreplace, cmd2, cmd2, %A_space%,`n
filedelete, Settings\tempcheck.txt
fileappend, %cmd2%, Settings\tempcheck.txt
filereadline, nameinc, Settings\tempcheck.txt, 1
filereadline, msginc, Settings\tempcheck.txt, 2
msginc2= [Private] (From: $ChatServer) %msginc%
filedelete, Settings\tempcheck.txt
loop, read, Settings\userlistpm.txt
{
currentline := A_Loopreadline
if nameinc=%currentline%
{
 SendData(conectioncheck%A_Index%,msginc2)
fileappend, [Private] (To: %nameinc%) %msginc% `n, Settings\server.txt
   fileread, chat2, Settings\server.txt
   guicontrol,,chat, %chat2%
   controlsend edit1, ^{end}, WinSock Chat Server
return
}

}
return
}

if Sendtext=/reg on
{
iniwrite, 1,Settings\users.ini, userSetting,allowAnoniumsReg
anonimuson=1
guicontrol,,chat,Registrations from anonimus users:  ON
guicontrol,,SendText,
return
}
if Sendtext=/reg off
{
iniwrite, 0,Settings\users.ini, userSetting,allowAnoniumsReg
anonimuson=0
guicontrol,,chat,Registrations from anonimus users:  OFF
guicontrol,,SendText,
return
}

if Sendtext=/info
{
guicontrol,,chat,%mainchattxt%
guicontrol,,SendText,
return
}

ifinstring, Sendtext,/edituser
{
Stringreplace, editusr,Sendtext,/edituser%a_space%
StringSplit, usr,editusr,%A_space%
if usr2<>
{
pass:=Encode(usr2, encryptpass)
iniread, isuser,Settings\users.ini, Users, %usr1%
if isuser<>ERROR
{
iniwrite, %pass%,Settings\users.ini, Users,%usr1%
guicontrol,,chat,User %usr1% password changed to %usr2%
}
else
{
guicontrol,,chat,User %usr1% does not exist! Do you want to create it?
MsgBox , 68, WinSock Chat,User %usr1% does not exist! Do you want to create it?
IfMsgBox Yes
    {
iniwrite, %pass%,Settings\users.ini, Users,%usr1%
guicontrol,,chat,User %usr1% with password %usr2% added to list
}

}
}
else
{
iniread, isuser,Settings\users.ini, Users, %usr1%
if isuser<>ERROR
{
passx:= Decode(isuser, encryptpass)
guicontrol,,chat,User %usr1% is registered with password %passx%
}
else
guicontrol,,chat,User %usr1% is not a registered user
}
reged=%maxusr%
guicontrol,,SendText,
return
}

ifinstring, Sendtext,/maxusers
{
Stringreplace, maxusr,Sendtext,/maxusers%a_space%
iniwrite, %maxusr%,Settings\users.ini, userSetting,allowMaxUsers
guicontrol,,chat,Maximum user registrations:  %maxusr%
usrsmax:= maxusr
guicontrol,,SendText,
return
}

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 , badstrings
    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%
         
         ifinstring, Showrecieved, 509SENDPM*
{
ShowRecieved2=%ShowRecieved%
stringtrimleft, ShowRecieved2, ShowRecieved2, 10
stringreplace, ShowRecieved2, ShowRecieved2,*,`n
stringreplace, ShowRecieved2, ShowRecieved2,*,`n
filedelete, Settings\privmsgtemp.txt
fileappend, %ShowRecieved2%, Settings\privmsgtemp.txt
filereadline, from2, Settings\privmsgtemp.txt, 1
filereadline, to2, Settings\privmsgtemp.txt, 2
filereadline, msg2, Settings\privmsgtemp.txt, 3
filedelete, Settings\privmsgtemp.txt
if to2=$
{
fileappend, [Private] (From: %from2%) %msg2%`n, Settings\server.txt
   fileread, chat2, Settings\server.txt
   guicontrol,,chat, %chat2%
   controlsend edit1, ^{end}, WinSock Chat Server
gooutmsg2=
to2=
from2=
msg2=
ShowRecieved =
return 1
}
gooutmsg2=[Private] (From: %from2%) %msg2%
loop, read, Settings\userlistpm.txt
{
currentline := A_Loopreadline
if to2=%currentline%
{
 SendData(conectioncheck%A_Index%,gooutmsg2)
fileappend, [Private] (To: %to2%) (From: %from2%) %msg2%`n, Settings\server.txt
   fileread, chat2, Settings\server.txt
   guicontrol,,chat, %chat2%
   controlsend edit1, ^{end}, WinSock Chat Server
gooutmsg2=
to2=
from2=
msg2=
ShowRecieved =
return 1
}

}
return 1
}
   ifnotinstring, Showrecieved, :
{
gosub, redirects
}

ifnotinstring , Showrecieved, LOGO
   {
   ifnotinstring , badstrings, %Showrecieved%
   fileappend, %ShowRecieved%`n,Settings\server.txt
   }
   fileread, chat2,Settings\server.txt
   Stringreplace, chat2, chat2,`n`n,`n
   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:
;#################### User management code #############################
ifinstring, Showrecieved, DOLOGIN1
{
StringSplit, recievedx, Showrecieved,@
Stringreplace, recievedx2, recievedx2, DOLOGIN1
Stringreplace, recievedx2, recievedx2,%a_space%
;if recievedx1=Anonimus
ifinstring, recievedx1,Anonimus
{
if anonimuson=1
{
if reged<%usrsmax%
{
Stringreplace, REGID, recievedx1, Anonimus
ShowRecieved=USRREG%REGID%
return
}
else
{
ShowRecieved=USRMAXREG
return
}
}
else
{
ShowRecieved=NOUSRREG
return
}
}
else
{
if recievedx1=Username
{
ShowRecieved=505NOSTANDARDLOGIN
return
}
else
{
iniread, pass,Settings\users.ini, Users, %recievedx1%
data:=recievedx2
if ( pass = data )
{
fileappend, %recievedx1%`n, Settings\userlist.txt
fileread, userlist, Settings\userlist.txt
fileappend, %recievedx1%`n, Settings\userlistpm.txt
guicontrol,,chatlist, %userlist%
stringreplace,userlist,userlist,`n,*,All
sleep, 500
Sendtext=SR1CLIENTADDLIST%userlist%
gosub, send1
name1=
cord=
ShowRecieved=
(
LOGO%logo%
)
;return
}
else
{
ShowRecieved=%recievedx1% notvaliduserorpass!
}
}
}
return
}

;#################### EO User management code #############################

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!
{
if name1<>Anonimus
{
fileappend, %recievedx1%`n, Settings\userlist.txt
fileread, userlist, Settings\userlist.txt
fileappend, %name1%`n, Settings\userlistpm.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
filedelete, Settings\userlistpm.txt
fileappend, %dellist2%,Settings\userlist.txt
fileread, userlist,Settings\userlist.txt
*/
fileread, dellist, Settings\userlist.txt
fileread, dellist5, Settings\userlistpm.txt
stringreplace, dellist6, dellist5, %name1%, %A_Space%
stringreplace, dellist2, dellist, %name1%`r`n

filedelete, Settings\userlist.txt
filedelete, Settings\userlistpm.txt
fileappend, %dellist2%, Settings\userlist.txt
fileappend, %dellist6%, Settings\userlistpm.txt
fileread, userlist, Settings\userlist.txt
guicontrol,,chatlist, %userlist%
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
fileread, dellist5, Settings\userlistpm.txt
stringreplace, dellist6, dellist5, %name1%, %A_Space%
stringreplace, dellist2, dellist, %name1%`r`n

filedelete, Settings\userlist.txt
filedelete, Settings\userlistpm.txt
fileappend, %dellist2%, Settings\userlist.txt
fileappend, %dellist6%, Settings\userlistpm.txt
fileread, userlist, Settings\userlist.txt
guicontrol,,chatlist, %userlist%
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
filedelete, Settings\userlistpm.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
fileread, dellist5, Settings\userlistpm.txt
stringreplace, dellist6, dellist5, %name1%, %A_Space%
stringreplace, dellist2, dellist, %name1%`r`n

filedelete, Settings\userlist.txt
filedelete, Settings\userlistpm.txt
fileappend, %dellist2%, Settings\userlist.txt
fileappend, %dellist6%, Settings\userlistpm.txt
fileread, userlist, Settings\userlist.txt
guicontrol,,chatlist, %userlist%
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
filedelete, Settings\userlistpm.txt
DllCall("Ws2_32\WSACleanup")
ExitApp

guiclose:
filedelete,Settings\userlist.txt
filedelete,Settings\server.txt
filedelete, Settings\userlistpm.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)
}

;main function initializeini(inifile = "ast.ini") by superfraggle at http://www.autohotkey.com/forum/viewtopic.php?t=21346

userreged(inifile = "settings/users.ini"){
  inisections:=0
  loop,read,%inifile%
  {
    if regexmatch(A_Loopreadline,"\[(.*)?]")
      {
        inisections+= 1
        section%inisections%:=regexreplace(A_loopreadline,"(\[)(.*)?(])","$2")
        section%inisections%_keys:=0
      }
    else if regexmatch(A_LoopReadLine,"(\w+)=(.*)")
      {
        section%inisections%_keys+= 1
        key:=section%inisections%_keys
        section%inisections%_key%key%:=regexreplace(A_LoopReadLine,"(\w+)=(.*)","$1")
      }
  }
  return %section1_keys%
}

Encode(Text, Key)
 {
  cKey := Key                                 ;Create copy of "Key"
  if % StrLen(Key) < StrLen(Text)             ;Need "Key" length to be same as or bigger than "Text"
   Loop
    {
     cKey .= Key                              ;Key * 2
     if % StrLen(cKey) >= StrLen(Text)
      break
    }
 
  Loop % StrLen(Text)
   {
    StringMid, t_%A_Index%, Text, %A_Index%, 1         ;Get ASCII value of Text, and ASCII value of Key
    StringMid, k_%A_Index%, cKey, %A_Index%, 1         ;then begin to add the values individially ex//
    cText.= Chr(Asc(k_%A_Index%) + Asc(t_%A_Index%))   ;Key = ab, Text = cd. Get ASCII value of a, then
   }                                                   ;add it to ASCII value of c, get ASCII value of
  return cText                                         ;b and add to ASCII value of d
 }
 
 Decode(Text, Key)
 {
  cKey := Key
  if % StrLen(Key) < StrLen(Text)
   Loop
    {
     cKey .= Key
     if % StrLen(cKey) >= StrLen(Text)
      break
    }
 
  Loop % StrLen(Text)
   {
    StringMid, t_%A_Index%, Text, %A_Index%, 1
    StringMid, k_%A_Index%, cKey, %A_Index%, 1
    cText.= Chr(Asc(t_%A_Index%) - Asc(k_%A_Index%))
   }
  return cText
 }
 
 randomid(lenght="10")
 {
 loop,%lenght%
   {
      Random, nr_rand, 0, 9
      ;Random, char_rand, 97, 122 ;all lowercase a-z
      Random, char_rand, 97, 102 ;all lowercase a-f
      char := chr(char_rand)
      randomid .= char . nr_rand
   }

 return, randomid
 }
Back to top
View user's profile Send private message Visit poster's website
Guest






PostPosted: Mon Feb 22, 2010 3:28 pm    Post subject: Reply with quote

Thanks for this script and those who have added to it.

What I would love to see is a robust version with less features. I tried all weekend to create a version that would do what I needed for a project. However, for a newbie it is really tough to separate what is the foundation needed to communicate via TCP and which are the "chat" features. I would love to create a server-client pair where the server can send a given text %sendtext% to the multiple clients, and the clients can send to the server without it being rebroadcast. I tried some of the other TCP programs in the forums as a foundation but found most had trouble with multiple host or were even more complicated that this one.

One thing that I noticed was that when I would connect via telnet connection using "Putty" is that certain sections of old message strings would continue to be resent. If a string like...

"Larry: Hello everyone. What is up?"

were entered the string actually sent to clients by the server might be something like

"Larry: Hello everyone. What is up?arry: Hello everyone. What is up?arry: Hello everyone. What is up?arry: Hello everyone. What is up?"

The client and servers seem to know how to handle this, but it makes using this code as a foundation difficult to use.

Could anyone strip this code down to its essentials an still keep it robust?

Thanks
Back to top
WankaUSR



Joined: 14 Aug 2007
Posts: 86

PostPosted: Mon Feb 22, 2010 3:35 pm    Post subject: Reply with quote

can you be more specific? you want the message from the server to be viewed by all clients but the message from the clients to be viewed only by the server?
Back to top
View user's profile Send private message Visit poster's website
Guest






PostPosted: Mon Feb 22, 2010 4:54 pm    Post subject: Reply with quote

WankaUSR wrote:
can you be more specific? you want the message from the server to be viewed by all clients but the message from the clients to be viewed only by the server?


Thanks for responding WankaUSR. Yes exactly! Having less would both help us understand the TCP part better and would provide a more flexible foundation for future server-client projects that might vary from the traditional chat.

The tray menu is great and having the clientlist and kick on the server are useful for testing, but without all the other extras:

The clients don't need to know who is logged on so...
no sending out client list to clients
no need informing clients when a new client is connected
no need informing clients when a new client is disconnected
no sending our the kick list

No Private messages

The clients assume the server is talking so...
no need to append "$ChatServer: " to outgoing messages

Perhaps most importantly eliminate the redundancy in the sent text (as viewable by telnet).

Also is the server able to tell if the client is really logged on or just if the client has "logged off". It would be nice if the server could remove the client from the list anytime the connection was actually closed or lost. Seems like I saw a solution for this in one of the other AHK chat threads if not in this one.

Thanks again
Back to top
WankaUSR



Joined: 14 Aug 2007
Posts: 86

PostPosted: Tue Feb 23, 2010 9:23 am    Post subject: Reply with quote

is this what you wanted? if so I will post the script if not tell what is wrong and try to fix it
Back to top
View user's profile Send private message Visit poster's website
rockum



Joined: 20 Dec 2007
Posts: 22

PostPosted: Wed Feb 24, 2010 4:54 am    Post subject: Reply with quote

Yes that looks great. Looking forward to seeing the code.
Back to top
View user's profile Send private message
rockum



Joined: 20 Dec 2007
Posts: 22

PostPosted: Thu Feb 25, 2010 2:33 pm    Post subject: Reply with quote

BTW, I am "Guest". I don't know why I have had trouble staying logged on at work.
Back to top
View user's profile Send private message
Tuncay



Joined: 07 Nov 2006
Posts: 1886
Location: Germany

PostPosted: Thu Feb 25, 2010 9:50 pm    Post subject: Reply with quote

rockum wrote:
BTW, I am "Guest". I don't know why I have had trouble staying logged on at work.

Sometimes I have same problem. Mostly the Cookie/s with the login data is lost. This is just a hint, it can have many reason when the Cookie is deleted. good luck
_________________
{1:"ahkstdlib", 2:"my libs", 3:"my apps", 4:"my license"}
--> Don't feed the troll! <--
Back to top
View user's profile Send private message Send e-mail Visit poster's website
WankaUSR



Joined: 14 Aug 2007
Posts: 86

PostPosted: Fri Feb 26, 2010 1:27 pm    Post subject: Reply with quote

I have some problems with my laptop where all the scripts are and will be a couple of days before I can recover them so please wait for it
Back to top
View user's profile Send private message Visit poster's website
Lexikos



Joined: 17 Oct 2006
Posts: 7299
Location: Australia

PostPosted: Fri Feb 26, 2010 2:48 pm    Post subject: Reply with quote

rockum as Guest wrote:
However, for a newbie it is really tough to separate what is the foundation needed to communicate via TCP and which are the "chat" features.
You might like to take a look at DerRaphael's WinSock2 library (script), which covers the fundamentals of TCP/IP communication.
Back to top
View user's profile Send private message Visit poster's website
rockum



Joined: 20 Dec 2007
Posts: 22

PostPosted: Mon Mar 01, 2010 11:42 pm    Post subject: Reply with quote

WankaUSR wrote:
I have some problems with my laptop where all the scripts are and will be a couple of days before I can recover them so please wait for it


no problem, looking forward to it.

@lexikos - thanks for the heads up...
Back to top
View user's profile Send private message
WankaUSR



Joined: 14 Aug 2007
Posts: 86

PostPosted: Tue Mar 02, 2010 12:04 pm    Post subject: Reply with quote

here is the code:
Client:
Code:

#singleinstance force
;#notrayicon
ifnotexist, Settings
{
Filecreatedir, Settings
}

menu, tray, icon, %A_Windir%\system32\narrator.exe
menu, tray, nostandard
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=%A_Computername%
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
}
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 w385 h140 readonly vchat,
Gui, Add, Edit, x6 y155 w385 h20 vSendText,
Gui, Add, Edit, x6 y185 w130 h20 limit12 vClientName, %ClientName%
Gui, Add, Button, x146 y185 w80 h20 vsendbutton gSendviaNet, Send
Gui, Add, Button, x236 y185 w70 h20 vconnect gConnection_Init, Connect
;Gui, Add, Edit, x276 y5 w110 h140 readonly vuserlistin,
Gui, Add, Button, x316 y185 w70 h20 vedit gdiscon, Log Out
guicontrol, disable, edit
Gui, Show, h218 w394, WinSock Chat Client
WinGet Gui_ID, ID, WinSock Chat 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 on=1
{
Msgbox, 16, WinSock Chat Client, Cannot configure when connected!
return
}
else
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
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


check:
return
/*
if on=0
{
Settimer,check,off
return
}
if on=1
{
ifnotinstring, userlistin, %Clientname%
{
Settimer,check,off
Msgbox, 16, WinSock Chat Client, Secure Link Could not be established. Please Restart Client
exitapp
}
guicontrol, enable, edit
Settimer,check,off
}
*/

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

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

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

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

Connection_Init:
gui, submit, nohide
ifinstring, Clientname, %A_Space%
{
Msgbox, 16, WinSock Chat Client, You cannot use spaces in your name!
return
}
ifinstring, Clientname, *
{
Msgbox, 16, WinSock Chat Client, You cannot use asteriks in your name!
return
}
ifinstring, Clientname, RX2
{
Msgbox, 16, WinSock Chat Client, You cannot use that in your name!
return
}
ifinstring, Clientname, SR1
{
Msgbox, 16, WinSock Chat Client, You cannot use that in your name!
return
}
ifinstring, Clientname, :
{
Msgbox, 16, WinSock Chat Client, You cannot use colons in your name!
return
}
ifinstring, Clientname, $
{
Msgbox, 16, WinSock Chat 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, WinSock Chat 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
}
;menu, tray, delete, Configure
guicontrol,,chat,
guicontrol, disable, edit
guicontrol,hide, connect
guicontrol, hide, clientname
guicontrol, move, sendbutton, x6 y185 w300 h20
OnExit, ExitSub


DllCall("Ws2_32\WSACleanup")


socket := ConnectToAddress(Network_Address, Network_Port)
if socket = -1
    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
}
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.
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}, WinSock Chat 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
}
}
}
*/
sendtext2=%sendtext%
stringmid, sendtext2, sendtext2, 0, 4
if sendtext2=/msg
{
guicontrol,,SendText,
stringtrimleft, cmd2, sendtext, 5
stringreplace, cmd2, cmd2, %A_space%,`n
filedelete, Settings\tempcheckc.txt
fileappend, %cmd2%, Settings\tempcheckc.txt
filereadline, nameinc, Settings\tempcheckc.txt, 1
if nameinc=%Clientname%
{
tooltip, You cannot send a message to yourself!, 220, 180
Settimer, removetooltip, 4000
filedelete, Settings\tempcheckc.txt
return
}
filereadline, msginc, Settings\tempcheckc.txt, 2
ifinstring, msginc, *
{
tooltip, Please do not use asteriks in your message!, 220, 180
filedelete, Settings\tempcheckc.txt
return
}
/*
msginc2=509SENDPM*%Clientname%*%nameinc%*%msginc%
filedelete, Settings\tempcheckc.txt
loop, read, Settings\userlistc.txt
{
currentline := A_Loopreadline
if nameinc=%currentline%
{

 SendData(socket,msginc2)
fileappend, [Private] (To: %nameinc%) %msginc% `n, Settings\client.txt
   fileread, chat1, Settings\client.txt
   guicontrol,,chat, %chat1%
           ControlSend Edit1, ^{End}, WinSock Chat Client

return
}
if nameinc=$
{

 SendData(socket,msginc2)
fileappend, [Private] (To: $ChatServer) %msginc% `n, Settings\client.txt
   fileread, chat1, Settings\client.txt
   guicontrol,,chat, %chat1%
           ControlSend Edit1, ^{End}, WinSock Chat Client

return
}
}
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
}
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
    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
        }

        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
   return
   }

}

 fileappend, %ShowRecieved%`n, Settings\client.txt
   fileread, chat1, Settings\client.txt
   guicontrol,,chat, %chat1%
    ShowRecieved =
        ControlSend Edit1, ^{End}, WinSock Chat Client
   ifwinnotactive, WinSock Chat 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:
return
/*
ShowRecieved2=%ShowRecieved%
ifinstring, Showrecieved2, RX2KICKPLAYER
{
stringreplace, Showrecieved2, Showrecieved2, RX2KICKPLAYER,-,All
if Showrecieved2=-%clientname%
   {
gosub, kickexit
   }
Showrecieved=
exit
}
ifinstring, ShowRecieved2, connected!
{
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%
filedelete, Settings\usernamestemp.txt
fileappend, %userlist2%, Settings\usernamestemp.txt
if checkornot=0
{
firsthit=0
Loop, read, Settings\usernamestemp.txt
{
    last_line := A_LoopReadLine
if last_line=%clientname%
{
if firsthit=0
{
firsthit=1
continue
}
guicontrol,,userlistin,
sleep, 500
nam=1
filedelete, Settings\usernamestemp.txt
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
if nam=1
{
Msgbox, 16, WinSock Chat Client, Client name already in use!
exitapp
}
ExitApp


discon:
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
guicontrol,,userlistin,
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, disable, edit
guicontrol,show, connect
guicontrol, show, clientname
guicontrol, move, sendbutton, x146 y185 w80 h20
guicontrol,disable,connect
settimer, disableenable, 2000
configurex=1
filedelete,Settings\userlistc.txt
filedelete, Settings\client.txt
filedelete, Settings\i2l.txt
filedelete, Settings\usernamestemp.txt
return

disableenable:
settimer, disableenable, off
guicontrol,enable, connect
return

Kickexit:
gui, destroy
open= %Clientname% was kicked!
SendData(socket,open)
sleep, 500
DllCall("Ws2_32\WSACleanup")
Msgbox, 16, WinSock Chat Client, You were kicked from the Server!
exitapp

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

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

Server:
Code:

#singleinstance force
;#notrayicon
ifnotexist, Settings
{
Filecreatedir, Settings
}

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, 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 gSendviaNet, Send
Gui, Add, edit, x306 y204 w70 h20 vkicknick,
Gui, Add, Button, x386 y204 w80 h20 vkick gkick_player, Kick
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

Gosub Connection_Init

return

buttonhide:
winhide, WinSock Chat Server
return

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

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

$Enter::
ifwinactive, WinSock Chat 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..., Settings\server.txt
   fileread, chat2, Settings\server.txt
   guicontrol,,chat, %chat2%
   controlsend edit1, ^{end}, WinSock Chat Server
   Sendtext= RX2CLIENTCON:
   gosub, Send1
   Sendtext=
    }
    sleep 500
}   
return


SendviaNet:
Gui, Submit, NoHide
stringmid, cmd2, sendtext, 0, 4
if cmd2=/msg
{
guicontrol,,SendText,
stringtrimleft, cmd2, sendtext, 5
stringreplace, cmd2, cmd2, %A_space%,`n
filedelete, Settings\tempcheck.txt
fileappend, %cmd2%, Settings\tempcheck.txt
filereadline, nameinc, Settings\tempcheck.txt, 1
filereadline, msginc, Settings\tempcheck.txt, 2
msginc2= [Private] (From: $ChatServer) %msginc%
filedelete, Settings\tempcheck.txt
loop, read, Settings\userlistpm.txt
{
currentline := A_Loopreadline
if nameinc=%currentline%
{

 SendData(conectioncheck%A_Index%,msginc2)
fileappend, [Private] (To: %nameinc%) %msginc% `n, Settings\server.txt
   fileread, chat2, Settings\server.txt
   guicontrol,,chat, %chat2%
   controlsend edit1, ^{end}, WinSock Chat Server
return
}

}
return
}



;SendText =$ChatServer: %SendText%
SendText =%SendText%
guicontrol,,SendText,
go:
fileappend, %SendText%`n, Settings\server.txt
   fileread, chat2, Settings\server.txt
   guicontrol,,chat, %chat2%
   controlsend edit1, ^{end}, WinSock Chat 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%
ifinstring, Showrecieved, 509SENDPM*
{
ShowRecieved2=%ShowRecieved%
stringtrimleft, ShowRecieved2, ShowRecieved2, 10
stringreplace, ShowRecieved2, ShowRecieved2,*,`n
stringreplace, ShowRecieved2, ShowRecieved2,*,`n
filedelete, Settings\privmsgtemp.txt
fileappend, %ShowRecieved2%, Settings\privmsgtemp.txt
filereadline, from2, Settings\privmsgtemp.txt, 1
filereadline, to2, Settings\privmsgtemp.txt, 2
filereadline, msg2, Settings\privmsgtemp.txt, 3
filedelete, Settings\privmsgtemp.txt
if to2=$
{
fileappend, [Private] (From: %from2%) %msg2%`n, Settings\server.txt
   fileread, chat2, Settings\server.txt
   guicontrol,,chat, %chat2%
   controlsend edit1, ^{end}, WinSock Chat Server
gooutmsg2=
to2=
from2=
msg2=
ShowRecieved =
return 1
}
gooutmsg2=[Private] (From: %from2%) %msg2%
loop, read, Settings\userlistpm.txt
{
currentline := A_Loopreadline
if to2=%currentline%
{
 SendData(conectioncheck%A_Index%,gooutmsg2)
fileappend, [Private] (To: %to2%) (From: %from2%) %msg2%`n, Settings\server.txt
   fileread, chat2, Settings\server.txt
   guicontrol,,chat, %chat2%
   controlsend edit1, ^{end}, WinSock Chat Server
gooutmsg2=
to2=
from2=
msg2=
ShowRecieved =
return 1
}

}
return 1
}
   ifnotinstring, Showrecieved, :
{
gosub, redirects
}


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

SendData(wParam,SendData)
{
socket := wParam
;fileappend, %socket%`n, %A_Desktop%\socketlst.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:
ifinstring, Showrecieved, kicked!
{
return
}
ShowRecieved2=%ShowRecieved%
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
ShowRecieved=
if cord=connected!
{
fileappend, %name1%`n, Settings\userlist.txt
fileappend, %name1%`n, Settings\userlistpm.txt
fileread, userlist, Settings\userlist.txt
guicontrol,,chatlist, %userlist%
stringreplace,userlist,userlist,`n,*,All
sleep, 500
;Sendtext=SR1CLIENTADDLIST%userlist%
;gosub, send1
ShowRecieved= ; received data is now null ready for new data
name1=
cord=
return
}
if cord=disconnected!
{
fileread, dellist, Settings\userlist.txt
fileread, dellist5, Settings\userlistpm.txt
stringreplace, dellist6, dellist5, %name1%, %A_Space%
stringreplace, dellist2, dellist, %name1%`r`n

filedelete, Settings\userlist.txt
filedelete, Settings\userlistpm.txt
fileappend, %dellist2%, Settings\userlist.txt
fileappend, %dellist6%, Settings\userlistpm.txt
fileread, userlist, Settings\userlist.txt
guicontrol,,chatlist, %userlist%
stringreplace,userlist,userlist,`n,*,All
;Sendtext=SR1CLIENTADDLIST%userlist%
;gosub, send1
ShowRecieved= ; received data is now null ready for new data
name1=
cord=
return
}
ShowRecieved=
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
fileread, dellist5, Settings\userlistpm.txt
stringreplace, dellist6, dellist5, %name1%, %A_Space%
stringreplace, dellist2, dellist, %kicknick%`r`n

filedelete, Settings\userlist.txt
filedelete, Settings\userlistpm.txt
fileappend, %dellist2%, Settings\userlist.txt
fileappend, %dellist6%, Settings\userlistpm.txt
fileread, userlist, Settings\userlist.txt
guicontrol,,chatlist, %userlist%
stringreplace,userlist,userlist,`n,*,All
;Sendtext=SR1CLIENTADDLIST%userlist%
;gosub, send1
sendtext=
name1=
kicknick=
cord=
return

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

Exit:
exitapp

ExitSub:
gui, submit, nohide
if chatlist=
{
goto, end
}
Msgbox, 48, WinSock Chat 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\userlistpm.txt
filedelete, Settings\server.txt
filedelete,Settings\userlist.txt
DllCall("Ws2_32\WSACleanup")
ExitApp

guiclose:
filedelete, Settings\userlistpm.txt
filedelete,Settings\userlist.txt
filedelete, Settings\server.txt
exitapp
Back to top
View user's profile Send private message Visit poster's website
rockum



Joined: 20 Dec 2007
Posts: 22

PostPosted: Tue Mar 02, 2010 4:56 pm    Post subject: Reply with quote

cool looking forward to trying it out - thanks
Back to top
View user's profile Send private message
Display posts from previous:   
Reply to topic    AutoHotkey Community Forum Index -> Scripts & Functions All times are GMT
Goto page Previous  1, 2, 3, 4, 5, 6, 7, 8, 9  Next
Page 8 of 9

 
Jump to:  
You can post new topics in this forum
You can reply to topics in this forum


Powered by phpBB © 2001, 2005 phpBB Group