Ir para conteúdo
Fórum Script Brasil
  • 0

Conexão (Cliente/Servidor) Enviando Arquivo ?


Densyy

Pergunta

Então pessoal

Preciso de um meio no vb com a finalidade de transferencia de arquivos

para o cliete, Exemplo de Aplicação:

Servidor -> envia arquivos para o Cliente

Cliente -> Recebe o Arquivo

to tentando com o winsock , mas n deu em nada

Sobre os arquivos , são de qualquer tipo exemplo (txt,mp3...)

Agradeço desde já

Link para o comentário
Compartilhar em outros sites

4 respostass a esta questão

Posts Recomendados

  • 0

Densyy, você deve abrir o arquivo como binário (Open For Binary) e salvar os dados num array de Byte, como é feito no exemplo: http://stackoverflow.com/questions/2456110...e-into-an-array

Depois disso, se já tiver conseguido fazer funcionar as conexões do Winsock, deve ser só enviar o array com o .SendData() e receber com .GetData(), informando no parâmetro type que o tipo recebido deve ser um Byte Array.

Nunca tentei, mas imagino que funcione.

Depois de receber, você grava chama um outro Open For Binary, e dessa vez em vez de usar o Get (como no primeiro link que passei), você usar o Put pra fazer o caminho inverso (passar do array pro arquivo).

Mas no caso de arquivos grandes, acho melhor mandar aos poucos.

EDITADO:

Mas numa rede local, o FileCopy() também vai resolver, como sugeriu o Matheus - desde que haja as devidas permissões.

Editado por kuroi
Link para o comentário
Compartilhar em outros sites

  • 0

Como o Kuroi falou funciona 100%.

Tenho um projeto que faz justamente isso: passa para binario, coloca em uma array, e vai enviando por partes...pois todo não é possível.

Vou procurar o projeto e posto aqui como fica a Função que envia e a que recebe...só espero acha-lo :rolleyes:

Editado por Danleonhart
Link para o comentário
Compartilhar em outros sites

  • 0

Ae pessoal Vlw mesmo

Deu certo !!

Pra quem tiver com a mesma duvida aqui vai o Esquema que encontrei ->

Send Project:

Option Explicit
     
    Private iFileNum As Integer, lPacketSize As Long
     
    Private Sub Form_Load()
    On Error GoTo Err
        Winsock1.Close
        Winsock1.LocalPort = 1003
        Winsock1.Listen
        Me.Caption = "Listening: Port 1003"
        Exit Sub
    Err:
        MsgBox "Socket Error!" & vbNewLine & _
                Err.Description
        Unload Me
        Exit Sub
    End Sub
     
    Private Sub Form_Unload(Cancel As Integer)
        Winsock1.Close
        Timer1.Interval = 0
        Timer1.Enabled = False
    End Sub
     
    Private Sub Winsock1_Close()
        If Winsock1.State = sckClosing Then
            Winsock1.Close
        End If
    End Sub
     
    Private Sub Winsock1_ConnectionRequest(ByVal requestID As Long)
        If Winsock1.State <> sckClosed Then
            Winsock1.Close
        End If
        Winsock1.Accept requestID
        SendFile Winsock1, App.Path & "\tmp.jpg"
    End Sub
     
    Public Sub SendFile(SocketObject As Winsock, ByVal FilePath As String, Optional ByVal PacketSize As Long = 1024)
        Dim Buffer() As Byte
       
        lPacketSize = PacketSize ' save the PacketSize for the timer
        Timer1.Enabled = False ' make suze timer is not enabled
       
        iFileNum = FreeFile ' get free file number
        Open FilePath For Binary Access Read As iFileNum ' open file
       
        ' if file size is smaller than PacketSize, then send the whole file, but not more
        ReDim Buffer(lngMIN(LOF(iFileNum), PacketSize) - 1)
        Get iFileNum, , Buffer ' read data
       
        SocketObject.SendData Buffer ' send data
    End Sub
     
    Public Function lngMIN(ByVal L1 As Long, ByVal L2 As Long) As Long
        If L1 < L2 Then
            lngMIN = L1
        Else
            lngMIN = L2
        End If
    End Function
     
    Private Sub Winsock1_SendComplete()
        Timer1.Enabled = False
        Timer1.Interval = 1
        Timer1.Enabled = True
    End Sub
     
    Private Sub Timer1_Timer()
        Dim Buffer() As Byte, BuffSize As Long
        Timer1.Enabled = False
        If iFileNum <= 0 Then Exit Sub
        If Loc(iFileNum) >= LOF(iFileNum) Then ' FILE COMPLETE
            Close iFileNum ' close file
            iFileNum = 0 ' set file number to 0, timer will exit if another timer event
            BuffSize = 0
            Winsock1.Close
            Winsock1.LocalPort = 1003
            Winsock1.Listen
            Me.Caption = "Listening: Port 1003"
            Exit Sub
        End If
        'if the remaining size in the file is smaller then PacketSize, the read only whatever is left
        BuffSize = lngMIN(LOF(iFileNum) - Loc(iFileNum), lPacketSize)
        ReDim Buffer(BuffSize - 1) ' resize buffer
        Get iFileNum, , Buffer ' read data
        Winsock1.SendData Buffer ' send data
        ' Show progress
        Me.Caption = "Sending: " & Format(Loc(iFileNum) / CDbl(LOF(iFileNum)) * 100#, "#0.00") & "% Done"
        ' timer event will be called again when last packet is sent, close the file then
    End Sub
Receive Project;
Option Explicit
     
    '// PROGRAM SETTINGS
    Const TCP_IP                As String = "192.168.1.2"
    Const TCP_PORT              As Long = 1003
     
    Private ReceiveData         As String
    Private FileBytes           As Long
     
    '// CLOSE WINSOCK
    Private Sub Winsock1_Close()
        Dim strTempFile As String
        Dim intFile As Integer
        If Winsock1.State = sckClosing Then
            Winsock1.Close
        End If
        strTempFile = App.Path & "\tmp.jpg"
        intFile = FreeFile
        Open strTempFile For Binary As #intFile
        Put #intFile, , ReceiveData
        Close #intFile
        ReceiveData = ""
        Me.Caption = "Done"
    End Sub
     
    '// DATA ARRIVES
    Private Sub Winsock1_dataArrival(ByVal bytesTotal As Long)
        Dim strData As String
        Winsock1.GetData strData
        ReceiveData = ReceiveData & strData
        FileBytes = FileBytes + bytesTotal
        Me.Caption = "Downloading: " & FileBytes & " bytes"
    End Sub
     
    '// ERROR
    Private Sub Winsock1_Error(ByVal Number As Integer, Description As String, ByVal Scode As Long, _
    ByVal Source As String, ByVal HelpFile As String, ByVal HelpContext As Long, CancelDisplay As Boolean)
        Winsock1.Close
        MsgBox "Error Connecting!"
    End Sub
     
    '// FORM LOAD
    Private Sub Form_Load()
        Timer1.Enabled = True
        Timer1.Interval = 100
        With Winsock1
            .RemoteHost = TCP_IP
            .RemotePort = TCP_PORT
            .Connect
        End With
    End Sub
     
    '// UNLOAD FORM
    Private Sub Form_Unload(Cancel As Integer)
        Winsock1.Close
        Timer1.Interval = 0
        Timer1.Enabled = False
    End Sub

fonte: http://www.vbforums.com/showthread.php?416...les-via-winsock

Link para o comentário
Compartilhar em outros sites

Participe da discussão

Você pode postar agora e se registrar depois. Se você já tem uma conta, acesse agora para postar com sua conta.

Visitante
Responder esta pergunta...

×   Você colou conteúdo com formatação.   Remover formatação

  Apenas 75 emoticons são permitidos.

×   Seu link foi incorporado automaticamente.   Exibir como um link em vez disso

×   Seu conteúdo anterior foi restaurado.   Limpar Editor

×   Você não pode colar imagens diretamente. Carregar ou inserir imagens do URL.



  • Estatísticas dos Fóruns

    • Tópicos
      152k
    • Posts
      651,8k
×
×
  • Criar Novo...