Serveur:
► Afficher le texte
Code : Tout sélectionner
#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_Compression=4
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****
#include <EditConstants.au3>
#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>
Dim $disconnect, $disconnectAndExit
$password = "matwachich"
$ip = _GetIP()
$port = 8080
Opt("GUIOnEventMode", 1)
GUISetOnEvent($GUI_EVENT_CLOSE, "CLOSEClicked")
#Region ### START Koda GUI section ### Form=
$gui = GUICreate("Serveur", 296, 296)
$console = GUICtrlCreateEdit("", 8, 8, 281, 281, BitOR($ES_AUTOVSCROLL,$ES_AUTOHSCROLL,$ES_READONLY,$ES_WANTRETURN,$WS_HSCROLL,$WS_VSCROLL))
GUICtrlSetData(-1, "")
GUISetState(@SW_SHOW)
#EndRegion ### END Koda GUI section ###
;############# Starting TCP ###############
Global $disconnect = False
Global $desconnectAndExit = False
$ret = TCPStartup()
    If $ret = 0 Then Exit -1
$main_socket = TCPListen($ip, $port)
    If @error = 1 Then
        MsgBox(0, "Server", "Invalid IP!")
        Exit -1
    ElseIf @error = 2 Then
        MsgBox(0, "Server", "Invalid port!")
        Exit -1
    EndIf
;###########################################
Func CLOSEClicked()
    If $disconnect = False Then
        $disconnect = True
        $desconnectAndExit = True
    Else
        Exit 0
    EndIf
EndFunc
;############# Stand by Function ###########
Global $connected_socket = -1
_stand_by()
Func _stand_by()
    _toconsole("Server ready! (listening on "&$ip&":"&$port&")")
    $disconnect = True
    Do
        $connected_socket = TCPAccept($main_socket)
    Until $connected_socket <> -1
    _toconsole("Connection request")
    Sleep(1000)
    TCPSend($connected_socket, "30 sec to send password")
    _toconsole("Waiting password")
    $pass_timer = TimerInit()
    While 1
        $wait = TCPRecv($connected_socket, 100)
        If $wait = $password Then
            ExitLoop
        ElseIf TimerDiff($pass_timer) > 30000 Then
            TCPSend($connected_socket, "Delay expired, Stand by")
            _stand_by()
        ElseIf IsString($wait) And $wait <> $password And $wait <> "" Then
            TCPSend($connected_socket, "Invalid password")
        EndIf
    WEnd
    $disconnect = False
    TCPSend($connected_socket, "connection ok")
    _toconsole("Connected! ("&@HOUR&":"&@MIN&")")
    AdlibRegister("_getClientMsg", 0.1)
    Sleep (1000)
    While 1
        TCPSend($connected_socket, "Ping")
        Sleep(5000)
        If $disconnect = True Then ExitLoop
    WEnd
    AdlibUnRegister("_getClientMsg")
    TCPSend($connected_socket, "Server on stand-by")
    TCPCloseSocket($connected_socket)
    _toconsole("Disconnected! ("&@HOUR&":"&@MIN&")")
    If $desconnectAndExit = True Then Exit 0
    _stand_by()
EndFunc
;######################################################
;################# Receiving Function #################
Func _getClientMsg()
    $rcv = TCPRecv($connected_socket, 10000)
    Switch $rcv
        Case ""
            Return 0
        Case "disconnect"
            ConsoleWrite("disconnect received"&@CRLF)
            $disconnect = True
        ; Ici, on rajoute des cas: exemple, si le client envoi le méssage "truc", alor la fonction _truc() est appelé
    EndSwitch
    If $rcv <> "" Then _toconsole("Client: "&$rcv)
EndFunc
;##########################################################
;#################### Misc Functions ##########################
Func _toconsole($data)
    GUICtrlSetData($console, "> "&$data &@CRLF& GUICtrlRead($console))
EndFunc
Func _GetIP()
    Local $ip, $t_ip
    If InetGet("http://checkip.dyndns.org/?rnd1=" & Random(1, 65536) & "&rnd2=" & Random(1, 65536), @TempDir & "\~ip.tmp") Then
        $ip = FileRead(@TempDir & "\~ip.tmp", FileGetSize(@TempDir & "\~ip.tmp"))
        FileDelete(@TempDir & "\~ip.tmp")
        $ip = StringTrimLeft($ip, StringInStr($ip, ":") + 1)
        $ip = StringTrimRight($ip, StringLen($ip) - StringInStr($ip, "/") + 2)
        $t_ip = StringSplit($ip, '.')
        If $t_ip[0] = 4 And StringIsDigit($t_ip[1]) And StringIsDigit($t_ip[2]) And StringIsDigit($t_ip[3]) And StringIsDigit($t_ip[4]) Then
            Return $ip
        EndIf
    EndIf
    If InetGet("http://www.whatismyip.com/?rnd1=" & Random(1, 65536) & "&rnd2=" & Random(1, 65536), @TempDir & "\~ip.tmp") Then
        $ip = FileRead(@TempDir & "\~ip.tmp", FileGetSize(@TempDir & "\~ip.tmp"))
        FileDelete(@TempDir & "\~ip.tmp")
        $ip = StringTrimLeft($ip, StringInStr($ip, "Your ip is") + 10)
        $ip = StringLeft($ip, StringInStr($ip, " ") - 1)
        $ip = StringStripWS($ip, 8)
        $t_ip = StringSplit($ip, '.')
        If $t_ip[0] = 4 And StringIsDigit($t_ip[1]) And StringIsDigit($t_ip[2]) And StringIsDigit($t_ip[3]) And StringIsDigit($t_ip[4]) Then
            Return $ip
        EndIf
    EndIf
    Return SetError(1, 0, -1)
EndFunc   ;==>_GetIP
;##############################################################► Afficher le texte
Code : Tout sélectionner
#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_Compression=4
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****
#include <EditConstants.au3>
#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>
OnAutoItExitRegister("_onExit")
#Region ### START Koda GUI section ### Form=
$Form2 = GUICreate("Client", 296, 296)
$console = GUICtrlCreateEdit("", 8, 8, 281, 249, BitOR($ES_AUTOVSCROLL,$ES_AUTOHSCROLL,$ES_READONLY,$ES_WANTRETURN,$WS_HSCROLL,$WS_VSCROLL))
$b_connect = GUICtrlCreateButton("Connect", 8, 264, 89, 25, $WS_GROUP)
$b_sendMsg = GUICtrlCreateButton("Send message", 200, 264, 89, 25, $WS_GROUP)
GUISetState(@SW_SHOW)
#EndRegion ### END Koda GUI section ###
Global $connected_socket = -1
Global $connect_stat = False
Global $port = 8080
;############# Main loop #############################
While 1
    $msg = GUIGetMsg()
    Switch $msg
        Case $GUI_EVENT_CLOSE
            Exit 0
        Case $b_connect
            If GUICtrlRead($b_connect) = "Connect" Then
                _connect()
            ElseIf GUICtrlRead($b_connect) = "Disconnect" Then
                TCPSend($connected_socket, "disconnect")
                _toconsole("Disconnecting...")
            EndIf
        Case $b_sendMsg
            $TcpMsg = InputBox("Client", "Message to server", "")
            If $TcpMsg <> "" Then
            TCPSend($connected_socket, $TcpMsg)
        ; Ici, on rajoute des cas de gestion d'envoi au serveur, exemple: un bouton $truc, s'il est actionné, alor on envoi
        ; au serveur le méssage "truc".
        ; Ou alors, on envoi manuellement le message "truc" grace au bouton $b_sendMsg
            EndIf
    EndSwitch
WEnd
;##########################################################
;################ Connecting Functions ###################
Func _connect()
    $ip = InputBox("Client", "Enter server's IP", "")
    If $ip = "" Then Return
    _toconsole("Connection request to: "&$ip)
    $ret = TCPStartup()
        If $ret = 0 Then Return -1
    For $i = 0 To 10 Step 1
        $connected_socket = TCPConnect($ip, $port)
            If $connected_socket <> -1 And $connected_socket <> 0 Then
                ExitLoop
            ElseIf @error = 1 Then
                _toconsole("Invalid IP!")
                Return -1
            ElseIf @error = 2 Then
                _toconsole("Invalid port!")
                Return -1
            ElseIf $i = 10 Then
                _toconsole("Unable to connect after 10 attempts")
                Return -1
            EndIf
        _toconsole("Connection attempt "&$i)
        Sleep(5000)
    Next
    _toconsole("Connection to: "&$ip)
    AdlibRegister("_receive", 0.1)
EndFunc
Func _confirm_connection()
    _toconsole("confirmed ("&@HOUR&":"&@MIN&")")
    GUICtrlSetData($b_connect, "Disconnect")
    $connect_stat = True
    Return 0
EndFunc
;###############################################################
;################ Disconnect Function ##########################
Func _disconnect()
    TCPShutdown()
    _toconsole("Disconnected! ("&@HOUR&":"&@MIN&")")
    AdlibUnRegister("_receive")
    GUICtrlSetData($b_connect, "Connect")
    $connect_stat = False
EndFunc
;################################################################
;################### Receiving Function #########################
Func _receive()
    $recv = TCPRecv($connected_socket, 1000000)
    If $recv = "" Then Return
    Switch $recv
        Case "Server on stand-by"
            _disconnect()
        Case "connection ok"
            _confirm_connection()
        ; Ici, on rajoute la gestion de reception des messages du serveur, exemple: si on recoit le méssage "machin",
        ; alors on appel la fonction machin()
    EndSwitch
    If $recv <> "" And IsString($recv) Then _toconsole("Server: "&$recv)
    If $recv = "Ping" Then TCPSend($connected_socket, "Pong")
EndFunc
;################################################################
;#################### Misc Functions ############################
Func _toconsole($data)
    GUICtrlSetData($console, "> "&$data &@CRLF& GUICtrlRead($console))
EndFunc
Func _onExit()
    If $connect_stat = True Then
        TCPSend($connected_socket, "disconnect")
        While 1
            $rcv = TCPRecv($connected_socket, 100)
            If $rcv = "Server on stand-by" Then ExitLoop
        WEnd
        _toconsole("Serveur on stand by")
        _toconsole("Exiting...")
        Sleep(1000)
    Else
        Return 0
    EndIf
EndFunc
;#################################################################- Je sais que ce n'est pas complet mais c'est une excellente base!
- J'ai eu des problèmes avec la gestion du faite de quitter le script ($GUI_EVENT_CLOSE), mais je suis trop faignant pour le faire! je vous laisse le soin de le faire!
- Il n'y que quelques commentaires dans le code, ce sont les ESSENTIELS! Il faut les lires pour comprendre l'utilité du script! appart ça, le fonctionnement n'est pas commenté!
- Voici quand même une petit explication du fonctionnement
*On lance le serveur, il se met en écoute sur l'ip EXTERNE de la machine.
*On lance le client et on clique sur "connect", on entre l'ip sur laquelle écoute le serveur. La demande de connexion est partie, et le serveur attend le mot de passe! (Regardez dans le haut du code du serveur la variable $password!), pour envoyer au serveur le mot de passe (et n'importe quoi d'autre aussi) on clique sur Send dans le client, et on envoi le mot de passe.
*Une fois que c'est fait, la connexion est établie, et on peut voir la partie de ping-pong entre le serveur et le client!!!




