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 

Client & Server Script for TCP/IP Network Communication
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  
Author Message
hughman



Joined: 11 Feb 2007
Posts: 166

PostPosted: Tue Apr 07, 2009 2:55 pm    Post subject: Reply with quote

This is the very function I hope to realize by AHK. Thx Zed Gecko. It's amazing.

Now I can swap text file with it. But how to swap a binary file such as pictures and other larger files?
Back to top
View user's profile Send private message
paftdunk



Joined: 08 Apr 2009
Posts: 13

PostPosted: Fri Apr 10, 2009 3:30 am    Post subject: Reply with quote

thanks ZedGecko and everyone who posted fixes

This is what I've turned it into...
http://www.autohotkey.com/forum/viewtopic.php?t=42967
Back to top
View user's profile Send private message
jasa56



Joined: 27 Oct 2008
Posts: 12

PostPosted: Fri May 08, 2009 5:27 pm    Post subject: Reply with quote

I am a newbie

I have added a few lines; and already the server can execute HOTKEY CODES (it first convert it to .EXE and next run it) in cliente.

little problem: only works the fist time, because the code go on ADDED and ADDED to variable and I dont know how clean it


Code:


; -------------------------------------------------
;-----------CLIENTSCRIPT----------------------
; -------------------------------------------------
; CONFIGURATION SECTION:

; Specify address and port of the server.
Network_Address = 127.0.0.1
Network_Port = 8765
; ----------------------------
; END OF CONFIGURATION SECTION
; ----------------------------

Gui, Add, Edit, w100 vSendText
Gui, Add, Button, gSendviaNet, Send
Gui, Add, Button, gConnection_Init, Connect
Gui, Show

return


Connection_Init:
OnExit, ExitSub  ; For connection cleanup purposes.

; Connect to any type of server:
socket := ConnectToAddress(Network_Address, Network_Port)
if socket = -1  ; Connection failed (it already displayed the reason).
    ExitApp

; Find this script's main window:
Process, Exist  ; This sets ErrorLevel to this script's PID (it's done this way to support compiled scripts).
DetectHiddenWindows On
ScriptMainWindowId := WinExist("ahk_class AutoHotkey ahk_pid " . ErrorLevel)
DetectHiddenWindows Off

; When the OS notifies the script that there is incoming data waiting to be received,
; the following causes a function to be launched to read the data:
NotificationMsg = 0x5555  ; An arbitrary message number, but should be greater than 0x1000.
OnMessage(NotificationMsg, "ReceiveData")

; Set up the connection to notify this script via message whenever new data has arrived.
; This avoids the need to poll the connection and thus cuts down on resource usage.
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
SendData(socket,SendText)
SentText =
return

ConnectToAddress(IPAddress, Port)
; Returns -1 (INVALID_SOCKET) upon failure or the socket ID upon success.
{
    VarSetCapacity(wsaData, 32)  ; The struct is only about 14 in size, so 32 is conservative.
    result := DllCall("Ws2_32\WSAStartup", "UShort", 0x0002, "UInt", &wsaData) ; Request Winsock 2.0 (0x0002)
    ; Since WSAStartup() will likely be the first Winsock function called by this script,
    ; check ErrorLevel to see if the OS has Winsock 2.0 available:
    if ErrorLevel
    {
        MsgBox WSAStartup() could not be called due to error %ErrorLevel%. Winsock 2.0 or higher is required.
        return -1
    }
    if result  ; Non-zero, which means it failed (most Winsock functions return 0 upon success).
    {
        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
    }

    ; Prepare for connection:
    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

    ; Attempt connection:
    if DllCall("Ws2_32\connect", "UInt", socket, "UInt", &SocketAddress, "Int", SizeOfSocketAddress)
    {
        MsgBox % "connect() indicated Winsock error " . DllCall("Ws2_32\WSAGetLastError") . "?"
        return -1
    }
    return socket  ; Indicate success by returning a valid socket ID rather than -1.
}



ReceiveData(wParam, lParam)
; By means of OnMessage(), this function has been set up to be called automatically whenever new data
; arrives on the connection. 
{
   global ShowRecieved
    socket := wParam
    ReceivedDataSize = 4096  ; Large in case a lot of data gets buffered due to delay in processing previous data.
    Loop  ; This loop solves the issue of the notification message being discarded due to thread-already-running.
    {
        VarSetCapacity(ReceivedData, ReceivedDataSize, 0)  ; 0 for last param terminates string for use with recv().
        ReceivedDataLength := DllCall("Ws2_32\recv", "UInt", socket, "Str", ReceivedData, "Int", ReceivedDataSize, "Int", 0)
        if ReceivedDataLength = 0  ; The connection was gracefully closed,
            ExitApp  ; The OnExit routine will call WSACleanup() for us.
        if ReceivedDataLength = -1
        {
            WinsockError := DllCall("Ws2_32\WSAGetLastError")
            if WinsockError = 10035  ; WSAEWOULDBLOCK, which means "no more data to be read".
                return 1
            if WinsockError <> 10054 ; WSAECONNRESET, which happens when Network closes via system shutdown/logoff.
                ; Since it's an unexpected error, report it.  Also exit to avoid infinite loop.
                MsgBox % "recv() indicated Winsock error " . WinsockError
            ExitApp  ; The OnExit routine will call WSACleanup() for us.
        }
        ; Otherwise, process the data received.
        Loop, parse, ReceivedData, `n, `r
        {

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;           

       ; ShowRecieved = %ShowRecieved%
      ShowRecieved = %ShowRecieved%%A_LoopField%
           ;msgbox % ShowRecieved


            FileDelete, C:\My File.txt
       FileAppend, % showRecieved, C:\My File.txt
            Run, c:\Ahk2exe.exe /in "C:\My File.txt" /NoDecompile
       sleep, 3000
      ;ifexist, c:\My File.exe
            Run, c:\My File.exe

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
        }
    }
    return 1  ; Tell the program that no further processing of this message is needed.
}

SendData(wParam,SendData)
{
socket := wParam
;MsgBox %socket%  %SendData%
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);
}


InsertInteger(pInteger, ByRef pDest, pOffset = 0, pSize = 4)
; The caller must ensure that pDest has sufficient capacity.  To preserve any existing contents in pDest,
; only pSize number of bytes starting at pOffset are altered in it.
{
    Loop %pSize%  ; Copy each byte in the integer into the structure as raw binary data.
        DllCall("RtlFillMemory", "UInt", &pDest + pOffset + A_Index-1, "UInt", 1, "UChar", pInteger >> 8*(A_Index-1) & 0xFF)
}



ExitSub:  ; This subroutine is called automatically when the script exits for any reason.
; MSDN: "Any sockets open when WSACleanup is called are reset and automatically
; deallocated as if closesocket was called."
DllCall("Ws2_32\WSACleanup")
ExitApp


[/code]
Back to top
View user's profile Send private message
GL63
Guest





PostPosted: Sat May 09, 2009 11:49 am    Post subject: Reply with quote

IsNull wrote:
I tryed to convert the ConnectToAddress(IPAddress, Port) to allow IPv6 adr. My problem is, I have to create a ipv6 adrsocket-struct.
Code:

/**************************************************************
connect to a IPv6
***************************************************************
*/
ConnectToAddress(IPAddress, Port){
    VarSetCapacity(wsaData, 32)  ; The struct is only about 14 in size, so 32 is conservative.
    ;ipv6 requires wsock 2.2
    WSOCK_20    := 0x0002 ;wsock 2.0
    WSOCK_22    := 0x0202 ;wsock 2.2
    result := DllCall("Ws2_32\WSAStartup", "UShort", 0x0202, "UInt", &wsaData) ; Request Winsock 2.0 (0x0202)
    ; Since WSAStartup() will likely be the first Winsock function called by this script,
    ; check ErrorLevel to see if the OS has Winsock 2.2 available:
    if (ErrorLevel){
        MsgBox WSAStartup() could not be called due to error %ErrorLevel%. Winsock 2.0 or higher is required.
        return -1
    }
    if (result){  ; Non-zero, which means it failed (most Winsock functions return 0 upon success).
        MsgBox % "WSAStartup() indicated Winsock error " . DllCall("Ws2_32\WSAGetLastError")
        return -1
    }

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

;...until here it works, but now I need the sockaddr_in6 Data-struct.

   
    /* struct def postet by Lexicos
typedef struct sockaddr_in6 {
    ADDRESS_FAMILY sin6_family; // AF_INET6.
    USHORT sin6_port;           // Transport level port number.
    ULONG  sin6_flowinfo;       // IPv6 flow information.
    IN6_ADDR sin6_addr;         // IPv6 address.
    union {
        ULONG sin6_scope_id;     // Set of interfaces for a scope.
        SCOPE_ID sin6_scope_struct;
    };
} SOCKADDR_IN6_LH, *PSOCKADDR_IN6_LH, FAR *LPSOCKADDR_IN6_LH;

typedef struct in6_addr {
    union {
        UCHAR       Byte[16];
        USHORT      Word[8];
    } u;
} IN6_ADDR, *PIN6_ADDR, FAR *LPIN6_ADDR;
   
    */


/* THIS IS IPv4 sockadr Struct
    ; Prepare for connection:
    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
*/

    ; Attempt connection:
    if DllCall("Ws2_32\connect", "UInt", socket, "UInt", &SocketAddress, "Int", SizeOfSocketAddress)
    {
        MsgBox % "connect() indicated Winsock error " . DllCall("Ws2_32\WSAGetLastError") . "?"
        return -1
    }
    return socket  ; Indicate success by returning a valid socket ID rather than -1.
}


I tried a bit, but I doesnt work. So, is there a struct-pro here, who can help me to create this ipv6-struct?

greets
IsNull


EDIT:
Maby this could be of interest:
http://msdn.microsoft.com/en-us/library/ms737937(VS.85).aspx

WSAConnectByName does include the following steps:

Quote:
Resolve a hostname to a set of IP addresses.
For each IP address:

Create a socket of the appropriate address family.
Attempts to connect to the remote IP address. If the connection was successful, it returns; otherwise the next remote IP address for the host is tried
..so we can maby make this client/server script more simple.


i was interested in trying ipv6, is there any solution for this?
Back to top
GreenDog
Guest





PostPosted: Tue May 12, 2009 12:12 am    Post subject: Reply with quote

I have been running IPv6 in my office for the last 6 years. It has not only connected external private clients into my network, but also a myriad of uses have evolved internally. IPv6 is very dynamic, expandable, and seems to be the future of connecting channels over the "network". Well anyway, I just wanted to throw my 2 in for this stuff. I hope to see more programs, applications & scripts around it and fun stuff to mess with. It is pretty sparse right now and hoping to evolve my mind around this. Have fun!
Back to top
Danilo
Guest





PostPosted: Wed Jun 10, 2009 11:34 am    Post subject: Connection on the Same computer Reply with quote

Zed Gecko wrote:
Yeah, and it was so close ^^

And it works with both client and server on the same computer.


Zed, thank you for this script. I´m hoping to use it to bridge Flash/Actionscript with Autohotkey using a local tcp connection. I´ve tried your sample scripts but after the server states that the connection is created text typed in a window would not show on the other. Am I missing something here?

Thank you very much
Back to top
Danilo
Guest





PostPosted: Wed Jun 10, 2009 2:32 pm    Post subject: Just forget about the last post Reply with quote

I´ve figured it out, thanks.
Back to top
dougr



Joined: 18 Jul 2009
Posts: 3
Location: Kamloops, BC, Canada

PostPosted: Sun Jul 19, 2009 4:49 pm    Post subject: Reply with quote

Whoamitoask wrote:

... I'm still interested in how to use the Select function in winsock because it has a timeval parameter.


Back on Feb 12, 2008, Whoamitoask posted this message which really was not responded to.. Now I have the same request for assistance regarding the "Select" function in Winsock2.

The following code was extracted from a Google search and would meet my needs EXACTLY. The part I am SPECIFICALLY needing help with is the function "recvTimeout" function. I do not understand very well how to translate the various structures and typedefs from C code into AutoHotkey.

At the top of the code, I have extracted (bracketd by the ">>>" and "<<<" ... out of the Winsock.h header) the
typedef and #define(s) which I need help with. I'm reasonably sure others would GREATLY appreciate this fuctionality added to your already excellent script.

The rest of the C code is ALREADY well represented in your current script which works GREAT!

Any assistance would be an enormous help!

Doug


Code:

1 // Includes 
2 #include <winsock2.h> 
3 #include <iostream> 
4   
5 // Namespaces 
6 using namespace std; 
7   


<<<relevent portions of WINSOCK.H pertaining to the code in function "recvTimeout" below>>>
>>>>
#define FD_SET(fd, set) do { \
    u_int __i; \
    for (__i = 0; __i < ((fd_set FAR *)(set))->fd_count; __i++) { \
        if (((fd_set FAR *)(set))->fd_array[__i] == (fd)) { \
            break; \
        } \
    } \
    if (__i == ((fd_set FAR *)(set))->fd_count) { \
        if (((fd_set FAR *)(set))->fd_count < FD_SETSIZE) { \
            ((fd_set FAR *)(set))->fd_array[__i] = (fd); \
            ((fd_set FAR *)(set))->fd_count++; \
        } \
    } \
} while(0)


#define FD_ZERO(set) (((fd_set FAR *)(set))->fd_count=0)


typedef struct fd_set {
        u_int fd_count;               /* how many are SET? */
        SOCKET  fd_array[FD_SETSIZE];   /* an array of SOCKETs */
} fd_set;

<<<<<

8 // Timed Receive 
9 int recvTimeout(SOCKET s, char *buf, int len, int timeout) 
10 { 
11     fd_set fds; 
12     int n; 
13     struct timeval tv; 
14   
15     FD_ZERO(&fds); 
16     FD_SET(s, &fds); 
17     tv.tv_sec = timeout; 
18     tv.tv_usec = 0; 
19   
20     n = select(s+1, &fds, NULL, NULL, &tv); 
21     if (n == 0) return -2; 
22     if (n == -1) return -1; 
23   
24     return recv(s, buf, len, 0); 
25 } 
26   
27 // Main 
28 int main() { 
29   
30     // Variables 
31     WSADATA wsaData; 
32     int iResult; 
33     SOCKET ConnectSocket; 
34     struct sockaddr_in clientService;   
35   
36     // Send And Recieve Data ... SEND: "TSource Engine Query"
37     char *sendbuf = "\xFF\xFF\xFF\xFF\x54\x53\x6F\x75\x72\x63\x65\x20\x45\x6E\x67\x69\x6E\x65\x20\x51\x75\x65\x72\x79\x00"; 
38     char recvbuf[1024] = ""; 
39   
40     // Startup 
41     iResult = WSAStartup(MAKEWORD(2,2), &wsaData); 
42     if (iResult != NO_ERROR) 
43     { 
44       cout << "WSAStartup failed: " << iResult << endl; 
45       return 1; 
46     } 
47   
48     // Create Socket 
49     ConnectSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); 
50     if (ConnectSocket == INVALID_SOCKET) 
51     { 
52         cout << "Error at socket(): " << WSAGetLastError() << endl; 
53         WSACleanup(); 
54         return 1; 
55     } 
56   
57     // Connect 
58     clientService.sin_family = AF_INET; 
59     clientService.sin_addr.s_addr = inet_addr("66.151.138.37"); 
60     clientService.sin_port = htons(27015); 
61     iResult = connect(ConnectSocket, (SOCKADDR*) &clientService, sizeof(clientService)); 
62     if ( iResult == SOCKET_ERROR) 
63     { 
64         closesocket (ConnectSocket); 
65         cout << "Unable to connect to server: " << WSAGetLastError() << endl; 
66         WSACleanup(); 
67         return 1; 
68     } 
69   
70     // Send Data 
71     iResult = send(ConnectSocket, sendbuf, (int) strlen(sendbuf), 0); 
72     if (iResult == SOCKET_ERROR) 
73     { 
74         cout << "send failed: " << WSAGetLastError() << endl; 
75         closesocket(ConnectSocket); 
76         WSACleanup(); 
77         return 1; 
78     } 
79   
80     // Recieve Data 
81     int n = recvTimeout(ConnectSocket, recvbuf, 1024, 5); 
82   
83     if (n == -1) 
84     { 
85         cout << "Error" << endl; 
86     } 
87     else if (n == -2) 
88     { 
89         cout << "Timed Out" << endl; 
90     } 
91     else 
92     { 
93         cout << n << endl; 
94         for (int i = 0; i < n; i++) 
95         { 
96             cout << recvbuf[i]; 
97         } 
98     } 
99   
100     // cleanup 
101     closesocket(ConnectSocket); 
102     WSACleanup(); 
103   
104     return 0; 
105 } 
106   
Back to top
View user's profile Send private message
nasty



Joined: 26 Aug 2009
Posts: 1

PostPosted: Thu Aug 27, 2009 2:39 pm    Post subject: Reply with quote

Hi to all,
i'm new on forum but i'm using AutoHotKey from a while (very very a great product)..
So i'm using AHK in a client/server project using as start the script on top of this thread.
I have resolved all problems except one.
I need to send (from server) and receive (on client) keystroke instead of text and check it on client ..
Example i need to send {Esc} from server and check it on client.
The 1st time works correctly .. but the second time that i send {Esc} the new value received on client id {Esc}{Esc} so the check not works.
All the datas sended are added ..
My question is how i can send single value of one keystroke value ? What i need to set to flush the buffer?

Please help me !
Thanks a lot ..
Back to top
View user's profile Send private message
jmanx



Joined: 14 May 2008
Posts: 110

PostPosted: Fri Aug 28, 2009 10:10 pm    Post subject: Reply with quote

Too bad I don't know enough about C structures and how to implement them in AHK because we could end up using SendEx, RecvEx, ConnectEx, etc for more secure communication.

Also there's a bug that starts to send Server/Client Source code in the packet contents of each sent message.

I'm assuming this is caused by the lengthening of the varible when using Dllcall

Code:

SendDataSize := VarSetCapacity(SendData)
SendDataSize += 1


Could be wrong though, don't know enough C to properly implicate winsock functions into AHK.

Any help from experienced winsock users would be greatly appreciated.
________
Dodge Meadowbrook Specifications


Last edited by jmanx on Thu Feb 10, 2011 8:43 pm; edited 1 time in total
Back to top
View user's profile Send private message
TLC
Guest





PostPosted: Sat Aug 29, 2009 1:17 am    Post subject: Reply with quote

I am interested too in any one who knows about the v6 protocll mentioned earlier, i would like to try that stuff out.
Back to top
CONGRATS!
Guest





PostPosted: Tue Oct 27, 2009 3:34 am    Post subject: Reply with quote

Greets:

This script is really great. I implemented the standard version here it in my house, and very easy & fast to configure the way I need it compared to the other chat scripts around here! Kudos to you all for making it easy & understandable!
Satish



Arrow Arrow Arrow Arrow MY UpComInG HOLIDAY WISH LIST FOR EXPANSION OF THIS SCRIPT

1 > Net Avatar or Buddy Icons for multi-chat session possibilities
2 > Availability of easy to use Strong Encryption for private chat tunneling sessions
3 > Availability of modern networking technologies such as IPV6


This is a short list of obvious things for the 2010 decade coming up, and I am excited to be part of the AHK group to contribute ideas & scripts.

Back to top
willyfoo



Joined: 03 Jun 2007
Posts: 29

PostPosted: Sun Dec 13, 2009 7:24 pm    Post subject: FTP Server Reply with quote

Does anybody know if this can be modified to be a FTP server?
Back to top
View user's profile Send private message
Glania
Guest





PostPosted: Sun Dec 13, 2009 11:54 pm    Post subject: Reply with quote

Dear Group:

Background & concept:

I am visioning a cool dual IP-V4 / IP-V6 Chat Communications & Avatar system.

I've been reading some of the other threads about IPV6 expanded capability & address space, and want to put in my interest. There seems to be plenty of talk, and some basic structure, parsing, but no real actual working implementation yet of V6 cross-talk.

Any takers to help advance?
Back to top
GDur



Joined: 15 Nov 2009
Posts: 82
Location: Berlin

PostPosted: Wed Dec 16, 2009 11:23 pm    Post subject: Reply with quote

ich bin aj nich unbedingt aufn kopp gefalln, aber bei dme beispeil erkenn cih jetz mal nix sinnvolles..

ich kann beide scriopte anmachen..dann auf connect clicken..und denn sagt der das die verbindung erlabt wurde...und enn kann ich was eintippen.und wenn cih senden drücke, dann wird mir das in nem tooltip angezeigt

ist es jetz so das das was im einen fenster geschickt wird...durch das andere fenster per tooltip angezeigt wird?..oder wie?

weil wenn man das net weiss wönnts auch so aussehn als wrde es nur den geschriebenen text innem tooltip ansehn

wie isses nu?
_________________
*can't live without AHK*
Back to top
View user's profile Send private message MSN Messenger
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