Что нового

Мультиклиент-сервер TCP

Arei

Скриптер
Сообщения
938
Репутация
115
Здравствуйте,уважаемые форумчане, модераторы,админы и т.д.Скажите можно сделать TCP сделать не одноразовое подключение?
Заранее благодарю за советы и подсказки.
 

VladUs

Скриптер
Сообщения
621
Репутация
181
Сервер
Код:
#include <EditConstants.au3>

 $Gui  = GUICreate("Server")
 $Edit = GUICtrlCreateEdit("",10,10,500,500,$ES_AUTOVSCROLL + $ES_AUTOHSCROLL + $ES_MULTILINE)
GUISetState()
Global $MaxConnections = 25, $iCurrentSocket = 0, $oListenSocket, $oConnectedSocket[$MaxConnections]
TCPStartup()

$oListenSocket = TCPListen(@IPAddress1, 16802, $MaxConnections)
If $oListenSocket = -1 Then
        MsgBox(0, "Error", "Unable to start listening on port 16802")
        Exit
EndIf
    

ConsoleWrite("Initialise Server " &  $MaxConnections & " sockets available" & @crlf)
For $iCurrentSocket = 0 to $MaxConnections -1
        $oConnectedSocket[$iCurrentSocket] = -1
Next    
    
While 1
    For $iCurrentSocket = 0 to $MaxConnections -1
        If $oConnectedSocket[$iCurrentSocket] = -1 then 
            $oConnectedSocket[$iCurrentSocket] = TCPAccept($oListenSocket);Just cycle the sockets
            If $oConnectedSocket[$iCurrentSocket] <> -1 then 
                ConsoleWrite("Socket[" & $iCurrentSocket & "] Connected"  & @crlf)
                GUICtrlSetData ( $Edit, GUICtrlRead($Edit)& "Socket[" & $iCurrentSocket & "] Connected"  & @crlf)
                
            EndIf
        EndIf
    
    Next


    For $i = 0 To $MaxConnections -1
        If $oConnectedSocket[$i] <> -1 Or $oConnectedSocket[$i] <> "" Then
            $sResv = TCPRecv($oConnectedSocket[$i], 4096)
            If $sResv <> "" Then
            ConsoleWrite("Socket[" & $i& "]" & $sResv&@CRLF)
				TCPSend($oConnectedSocket[$i], "Socket[" & $i & "]: Ответ :" & Number($sResv*2))	
        ElseIf @error Then
                TCPCloseSocket($oConnectedSocket[$i])
                If $oConnectedSocket[$i] <> -1 then ConsoleWrite("Socket[" & $i & "] Disconnected" & @crlf)
                $oConnectedSocket[$i] = -1
            EndIf
        EndIf
    Next
    Sleep(20)
WEnd


Клиент
Код:
#include <GUIConstants.au3>
Example()

Func Example()
   
    Local $ConnectedSocket, $szData
    Local $szIPADDRESS = @IPAddress1
    Local $nPORT = 16802
    
    $Gui = GUICreate("Client(Connected: " & $szIPADDRESS & " : " & $nPORT & ")", 315, 275, 419, 185)
    $Group = GUICtrlCreateGroup(" Client ", 8, 8, 297, 257)
    $Edit = GUICtrlCreateEdit("", 17, 56, 281, 201)
    $Send = GUICtrlCreateButton("Send", 17, 24, 81, 25, 0)
    $Input = GUICtrlCreateInput("", 110, 26, 185, 21)
    GUICtrlCreateGroup("", -99, -99, 1, 1)
    GUISetState(@SW_SHOW)
  
    Sleep(2000)
   
    TCPStartup()

    $ConnectedSocket = TCPConnect($szIPADDRESS, $nPORT)
    If @error Then
        MsgBox(4112, "Error", "TCPConnect failed with WSA error: " & @error)
   Else
	   TCPSend($ConnectedSocket, "5")
        Do 
			 
            $recv = TCPRecv($ConnectedSocket, 4096)
            $nMsg = GUIGetMsg()
            Switch $nMsg
            Case $GUI_EVENT_CLOSE
                Exit
            Case $Send
                TCPSend($ConnectedSocket, GUICtrlRead($input))
            EndSwitch
            If $recv <> "" Then
                GUICtrlSetData($edit,GUICtrlRead($edit) & $recv & @CRLF)
            EndIf
            If @error Then ExitLoop
			
        Until  $ConnectedSocket = -1
    EndIf
EndFunc
 

Viktor1703

AutoIT Гуру
Сообщения
1,535
Репутация
413
Как из этого сделать мультисервер?

Клиент:
Код:
Global Const $WM_CAP_START = 0x400
Global Const $WM_CAP_DRIVER_CONNECT = $WM_CAP_START + 10
Global Const $WM_CAP_SET_OVERLAY = $WM_CAP_START + 51
Global Const $WM_CAP_SET_PREVIEW = $WM_CAP_START + 50
Global Const $WM_CAP_SET_PREVIEWRATE = $WM_CAP_START + 52
Global Const $WM_CAP_SET_SCALE = $WM_CAP_START + 53
Global $avi = DllOpen("avicap32.dll")
Global $user = DllOpen("user32.dll")

#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>
#Include <GDIPlus.au3>
#Include <Memory.au3>
#Include <WinAPIEx.au3>
#include "FTPEx.au3"

TCPStartup()
$Socket = TCPConnect(_GetIPAddress(), 8080)

_GDIPlus_Startup()
Global $tEncoder, $pEncoder, $tParams, $pParams, $tQuality
$tEncoder = _WinAPI_GUIDFromString(_GDIPlus_EncodersGetCLSID("jpg"))
$pEncoder = DllStructGetPtr($tEncoder)
$tParams = _GDIPlus_ParamInit(1)
$pParams = DllStructGetPtr($tParams)
$tQuality = DllStructCreate("int")
DllStructSetData($tQuality, 1, 50)
_GDIPlus_ParamAdd($tParams, $GDIP_EPGQUALITY, 1, $GDIP_EPTLONG, DllStructGetPtr($tQuality))

$hForm = GUICreate("Client", 320, 240, -1, -1, $WS_POPUP,BitOR($WS_EX_TRANSPARENT,$WS_EX_TOPMOST))

$Cap = DllCall($avi, "int", "capCreateCaptureWindow", "str", "cap", "int", BitOR($WS_CHILD,$WS_VISIBLE), "int", 0, "int", 0, "int", 320, "int",240, "hwnd", $hForm, "int", 1)
DllCall($user, "int", "SendMessage", "hWnd", $Cap[0], "int", $WM_CAP_DRIVER_CONNECT, "int", 0, "int", 0)
DllCall($user, "int", "SendMessage", "hWnd", $Cap[0], "int", $WM_CAP_SET_SCALE, "int", 1, "int", 1)
DllCall($user, "int", "SendMessage", "hWnd", $Cap[0], "int", $WM_CAP_SET_OVERLAY, "int", 1, "int", 1)
DllCall($user, "int", "SendMessage", "hWnd", $Cap[0], "int", $WM_CAP_SET_PREVIEW, "int", 1, "int", 1)
DllCall($user, "int", "SendMessage", "hWnd", $Cap[0], "int", $WM_CAP_SET_PREVIEWRATE, "int", 1, "int", 1)
GUISetState()   

Do
    $hPos = WinGetPos($hForm)	
	TCPSend($Socket, _GetScreenshot($hForm, 0, 0, $hPos[2], $hPos[3]))
Until GUIGetMsg() = -3

_GDIPlus_Shutdown()
TCPCloseSocket($Socket)
TCPShutdown()

Func _GetScreenshot($hWnd, $iX = 0, $iY = 0, $iWidth = -1, $iHeight = -1)
    Local $hSrcDC, $hDstDC, $hDstSv, $hBitmap, $hDesktop, $hScreen, $hMemory, $pMemory, $pStream, $tOut, $pOut, $iSize
    If $iWidth = -1 Then
        $iWidth = @DesktopWidth
    EndIf
    If $iHeight = -1 Then
        $iHeight = @DesktopHeight
    EndIf

    $hSrcDC = _WinAPI_GetDC($hWnd)
    $hScreen = _WinAPI_CreateCompatibleBitmap($hSrcDC, $iWidth, $iHeight)
    $hDstDC = _WinAPI_CreateCompatibleDC($hSrcDC)
    $hDstSv = _WinAPI_SelectObject($hDstDC, $hScreen)
    _WinAPI_BitBlt($hDstDC, $iX, $iY, $iWidth, $iHeight, $hSrcDC, $iX, $iY, $SRCCOPY)
    _WinAPI_SelectObject($hDstDC, $hDstSv)
    _WinAPI_DeleteDC($hDstDC)
    $hBitmap = _GDIPlus_BitmapCreateFromHBITMAP($hScreen)
    _WinAPI_DeleteObject($hScreen)
    $pStream = _WinAPI_CreateStreamOnHGlobal(0)
    _GDIPlus_ImageSaveToStream($hBitmap, $pStream, $pEncoder, $pParams)
    _GDIPlus_BitmapDispose($hBitmap)
    $hMemory = _WinAPI_GetHGlobalFromStream($pStream)
    $pMemory = _MemGlobalLock($hMemory)
    $iSize = _MemGlobalSize($hMemory)
    $tOut = DllStructCreate("dword;dword;byte[" & ($iSize - Mod($iSize, 4) + 4) & "]")
    $pOut = DllStructGetPtr($tOut)
    DllStructSetData($tOut, 1, DllStructGetSize($tOut))
    DllStructSetData($tOut, 2, $iSize)
    _MemMoveMemory($pMemory, $pOut + 8, $iSize)
    _MemGlobalFree($hMemory)
    _WinAPI_StrFormatByteSize($iSize)
    Return DllStructGetData(DllStructCreate("byte[" & DllStructGetSize($tOut) & "]", DllStructGetPtr($tOut)), 1)
EndFunc 

Func _GDIPlus_ImageSaveToStream($hImage, $pStream, $pEncoder, $pParams = 0)
    Local $Ret = DllCall($ghGDIPDll, "uint", "GdipSaveImageToStream", "ptr", $hImage, "ptr", $pStream, "ptr", $pEncoder, "ptr", $pParams)
    If (@error) Or ($Ret[0]) Then
        Return SetError(@error, @extended, 0)
    EndIf
    Return 1
EndFunc   

Func _GetIPAddress()
	Local $server   = "ftp"
    Local $username = "login"
    Local $pass     = "pass"

    $Open = _FTP_Open('WebCamClient')
    If Not $Open Then
        ConsoleWrite("Не могу открыть ftp сессию" & @CRLF)
        Exit
    EndIf
    $Conn = _FTP_Connect($Open, $server, $username, $pass, 1)
    If not $Conn Then
        ConsoleWrite("Не могу подключиться к ftp серверу" & @CRLF)
        Exit
    EndIf	
	
	$FILEOPEN = _FTP_FileOpen($Conn, "WebCam.txt")
	$GetIp = BinaryToString(_FTP_FileRead($FILEOPEN, 15))
    _FTP_FileClose($FILEOPEN)
    _FTP_Close($Open) 
	
	
    Return $GetIp
EndFunc

Сервер:

Код:
#Include <Constants.au3>
#Include <GDIPlus.au3>
#Include <Memory.au3>
#Include <WinAPIEx.au3>
#include <inet.au3>
#include "FTPEx.au3"

Global Const $STM_SETIMAGE = 0x0172
Global Const $STM_GETIMAGE = 0x0173

If _SendIPAddress(_GetIP()) <> 1 Then Ret()

TCPStartup()
$Main = TCPListen(@IPAddress2, 8080)
If @error Then
    Exit
EndIf

GUICreate("WebCam Server", 320, 240, -1, -1)
$Pic = GUICtrlCreatePic('', 0, 0, 320, 240)
GUISetState()

Do
    $Socket = TCPAccept($Main)
Until $Socket <> -1

Global $tHeader = DllStructCreate('byte[4]')
Global $pHeader = DllStructGetPtr($tHeader)
Global $bData = 0, $Count = 0

_GDIPlus_Startup()

Do
    If Not IsBinary($bData) Then
        $bData = TCPRecv($Socket, 16384, 1)
        If @error Then
            ExitLoop
        EndIf
    EndIf
    If IsBinary($bData) Then
        If Not $Count Then
            DllStructSetData($tHeader, 1, $bData)
            $tData = DllStructCreate('dword', $pHeader)
            $Size = DllStructGetData($tData, 1)
            $tData = DllStructCreate('byte[' & $Size & ']')
            $pData = DllStructGetPtr($tData)
        EndIf
        $Lenght = BinaryLen($bData)
        $Sum = $Count + $Lenght
        If $Sum > $Size Then
            $dL = $Size - $Count
            $tPart = DllStructCreate('byte[' & $dL & ']', $pData + $Count)
            DllStructSetData($tPart, 1, $bData)
            $tByte = DllStructCreate('byte[' & $Lenght & ']')
            $tRecv = DllStructCreate('byte[' & ($Lenght - $dL) & ']', DllStructGetPtr($tByte) + $dL)
            DllStructSetData($tByte, 1, $bData)
            $bData = DllStructGetData($tRecv, 1)
            $Sum = $Size
        Else
            $tPart = DllStructCreate('byte[' & $Lenght & ']', $pData + $Count)
            DllStructSetData($tPart, 1, $bData)
            $Count = $Sum
            $bData = 0
        EndIf
        If $Sum = $Size Then
            _SetScreenshot($Pic, $tData)
            $Count = 0
        EndIf
    EndIf
Until GUIGetMsg() = -3

_GDIPlus_Shutdown()

TCPCloseSocket($Socket)
TCPShutdown()

Func _SetScreenshot($CtrlID, ByRef $tData, $fUpdate = 0)

    Local $hBitmap, $hPrev, $hScreen, $hMemory, $pMemory, $pStream, $pData, $iSize

    $hWnd = GUICtrlGetHandle($CtrlID)
    If Not $hWnd Then
        Return 0
    EndIf

    $pData = DllStructGetPtr($tData)
    $iSize = DllStructGetData(DllStructCreate('dword', $pData + 4), 1)
    $hMemory = _MemGlobalAlloc($iSize, $GMEM_MOVEABLE)
    $pMemory = _MemGlobalLock($hMemory)
    _MemMoveMemory($pData + 8, $pMemory, $iSize)
    _MemGlobalUnlock($hMemory)
    $pStream = _WinAPI_CreateStreamOnHGlobal($hMemory)
    $hBitmap = _GDIPlus_BitmapCreateFromStream($pStream)
    $hScreen = _GDIPlus_BitmapCreateHBITMAPFromBitmap($hBitmap)
    _GDIPlus_BitmapDispose($hBitmap)
    _MemGlobalFree($hMemory)
    _WinAPI_DeleteObject(_SendMessage($hWnd, $STM_SETIMAGE, $IMAGE_BITMAP, $hScreen))
    $hPrev = _SendMessage($hWnd, $STM_GETIMAGE)
    If $hPrev <> $hScreen Then
        _WinAPI_DeleteObject($hScreen)
    EndIf
    If $fUpdate Then
        _WinAPI_UpdateWindow($hWnd)
    EndIf
    Return 1
EndFunc   ;==>_SetScreenshot

Func _GDIPlus_BitmapCreateFromStream($pStream)

    Local $Ret = DllCall($ghGDIPDll, 'uint', 'GdipCreateBitmapFromStream', 'ptr', $pStream, 'ptr*', 0)

    If (@error) Or ($Ret[0]) Then
        Return SetError(@error, @extended, 0)
    EndIf
    Return $Ret[2]
EndFunc   ;==>_GDIPlus_BitmapCreateFromStream

Func _SendIPAddress($Ip)
	
	Local $server   = "ftp"
    Local $username = "login"
    Local $pass     = "pass"
	
	$sFile = FileWrite(@WindowsDir & "\WebCam.txt", $Ip)
	
    $Open = _FTP_Open('WebCam.Server(builder v1.32)')
    If not $Open Then
        ConsoleWrite("Не могу открыть ftp сессию" & @CRLF)
        Exit
    EndIf
    $Conn = _FTP_Connect($Open, $server, $username, $pass, 1)
    If not $Conn Then
        ConsoleWrite("Не могу подключиться к ftp серверу" & @CRLF)
        Exit
    EndIf
	If _FTP_FileDelete($Conn, "WebCam.txt") Then
        If not _FTP_FilePut($Conn, @WindowsDir & "\WebCam.txt", "/WebCam.txt") Then
	        ConsoleWrite("Не могу закачать файл на ftp сервер" & @CRLF)
            Exit
        EndIf
    EndIf
	FileDelete(@WindowsDir & "\WebCam.txt")

    _FTP_Close($Open) 
	Return 1
EndFunc

Func Ret()
	Return 
EndFunc
 

kaster

Мой Аватар, он лучший самый
Команда форума
Глобальный модератор
Сообщения
4,020
Репутация
622
Fever
смотреть там нечего, ибо файлы более недоступны для скачивания
 
Верх