你看看 这个例子中 是怎么保存 文件的 :
用WINSOCK控件,用TCP/IP传文件:
===================================================================
http://www.csdn.net/expert/topic/546/546099.xml

解决方案 »

  1.   

    用 WinSock 控件下载文件1 增加一个 Winsock 控件, 名称为 Winsock1。
    2 建立连接:
    Winsock1.RemoteHost = "nease.com"
    Winsock1.RemotePort = 80
    Winsock1.Connect
    3 在Winsock1.Connect 事件中加入:Dim strCommand as String
    Dim strWebPage as String
    strWebPage = "http://www.nease.com/~kenj/index.html"
    strCommand = "GET " + strWebPage + " HTTP/1.0" + vbCrLf 
    strCommand = strCommand + "Accept: */*" + vbCrLf 
    strCommand = strCommand + "Accept: text/html" + vbCrLf 
    strCommand = strCommand + vbCrLf 
    Winsock1.SendData strCommand
    4 Winsock 开始下载, 在收到数据时, 发生DataArrival 事件。
    Dim webData As String 
    Winsock1.GetData webData, vbString
    TxtWebPage.Text = TxtWebPage.Text + webData
      

  2.   

    天呀,下载的.doc文档仍会出现无法辨认的格式,.bmp格式也不行,难道下载文件时不能用winsock?
      

  3.   

    //下面的代码既是服务器又是客户端
    //采用应答式发送方式
    //自动拆分文件,包括2进制'Usage:transfer a file to another pc through intranet with winsock power
    Option Explicit
    Dim mybyte() As Byte '发送方数组
    Const filecomesMSG = "a file is coming " '有文件到来
    Const RemoteIsReadyMSG = "I'm ready " '准备好了
    Const FileisOverMSG = "the file is ended" '文件完毕
    Const RemoteDenyMSG = "the user canceled"
    Const filecountMSG = "the file lengh is"
    Dim arrdata() As Byte '收到的信息
    Dim filesave As Integer '保存文件的句柄
    Dim filehandle As Integer '发送方文件的句柄
    Dim MyLocation As Double
    Dim myMSG As String '消息
    Dim FileisTransfer As Boolean '文件正在传送
    Dim Isendfile As Boolean '是否是本人在传送
    Dim FileisOver As Boolean '文件是否已经完毕
    Dim Counttime As Integer '需要传递的次数
    Dim totaltime As Variant
    Private Sub cmdsend_Click()
    On Error GoTo errorhandle
    'this is needed for correct filename
    filehandle = FreeFile
    If Mid(File1.Path, Len(File1.Path), 1) = "\" Then
    Open File1.Path & File1.FileName For Binary Access Read As #filehandle
    Else
    Open File1.Path & "\" & File1.FileName For Binary Access Read As #filehandle
    End If
    Isendfile = True '是本人在传送
    FileisOver = False '文件刚开始
    cmdsend.Enabled = False
    Label1.Caption = "Wait for reply..."
    MsgBox ("the selected file size is " & LOF(filehandle) & " bytes")
    totaltime = Int(LOF(filehandle) / 4000 + 1)
    MyLocation = Loc(filehandle)
    Winsock.SendData filecomesMSG & File1.FileName '发送发出文件信息
    Winsock.SendData filecountMSG & totaltime
    Exit Sub
    errorhandle: MsgBox ("You havn't choose a file!")
    End SubPrivate Sub Dir1_Change()
    File1.Path = Dir1.Path
    End SubPrivate Sub Drive1_Change()
    Dir1.Path = Drive1.Drive
    End SubPrivate Sub Form_Load()
    Drive1.Drive = "c:\"
    Winsock.RemoteHost = "255.255.255.255"
    Winsock.LocalPort = 7904
    Winsock.Bind 7904
    Winsockfile.RemoteHost = "255.255.255.255"
    Winsockfile.LocalPort = 7905
    Winsockfile.Bind 7905
    FileisTransfer = False 'initialize the bool value
    Isendfile = False
    FileisOver = True
    Counttime = 0
    Label1.Caption = "Ready..."
    End SubPrivate Sub Timer1_Timer()
    Dim i As Integer
    If LOF(filehandle) - MyLocation > 4000 Then
    ReDim mybyte(0 To 4000)
    Get #filehandle, , mybyte
    MyLocation = Loc(filehandle)
    Winsockfile.SendData mybyte
    Counttime = Counttime + 1
    Label1.Caption = "the select file is being transfered..." & "about " & Counttime & " / " & totaltime
    Timer1.Enabled = False
    Else
    ReDim mybyte(0 To LOF(filehandle) - MyLocation - 1)
    Get #filehandle, , mybyte
    Winsockfile.SendData mybyte
    FileisTransfer = False
    Timer1.Enabled = False
    FileisOver = True
    End IfEnd SubPrivate Sub Winsock_DataArrival(ByVal bytesTotal As Long)
    Winsock.GetData myMSG
    Select Case Mid(myMSG, 1, 17)
    Case filecomesMSG '这些消息发送方和接受方都可收到
    'do display a form
    If Not Isendfile Then '接受方处理这些事情
    On Error GoTo errorhandle
    CommonDialog1.FileName = Mid(myMSG, 17, Len(myMSG))
    CommonDialog1.ShowSave
    filesave = FreeFile
    FileisTransfer = True
    cmdsend.Enabled = False
    Open CommonDialog1.FileName For Binary Access Write As #filesave
    Winsock.SendData RemoteIsReadyMSG
    Label1.Caption = "the select file is being transfered..."
    End If
    Case RemoteIsReadyMSG
    'do begin transfer a file
    '如果文件还没有结束,也就是说,只有主机才能受到
    If Isendfile Then
    If Not FileisOver Then
    Timer1.Enabled = True
    Label1.Caption = "the select file is being transfered..."
    Else
    Winsock.SendData FileisOverMSG
    End If
    End If
    Case FileisOverMSG
    If Not Isendfile Then '客户机处理
    Close #filesave
    FileisTransfer = False
    Else '主机处理
    Isendfile = False
    Close #filehandle
    End If
    MsgBox ("the file is transfered successfully!") '大家一起处理
    Isendfile = False
    cmdsend.Enabled = True
    Label1.Caption = "Ready..."
    Case RemoteDenyMSG
    If Isendfile Then
    MsgBox ("The user canceled this transfer session!")
    Isendfile = False
    FileisOver = True
    cmdsend.Enabled = True
    Label1.Caption = "Ready..."
    Close #filehandle
    End If
    Case filecountMSG
    If Not Isendfile Then
    totaltime = Mid(myMSG, 17, Len(myMSG))
    End If
    End Select
    Exit Sub
    errorhandle: Winsock.SendData RemoteDenyMSG
    End Sub
    Private Sub writetofile()
    Put #filesave, , arrdata
    End SubPrivate Sub Winsockfile_DataArrival(ByVal bytesTotal As Long)
    If FileisTransfer Then
    Winsockfile.GetData arrdata, vbArray + vbByte, 4001
    writetofile
    Winsock.SendData RemoteIsReadyMSG
    Counttime = Counttime + 1
    Label1.Caption = "the select file is being transfered..." & "about " & Counttime & "/" & totaltime
    End If
    End Sub
      

  4.   

    再来。 又来一个。
    你帮我 up 一下。 我才好全部 帖完。
    还有 问题 ,在找我。 
    ================================================================
    VERSION 5.00
    Object = "{248DD890-BB45-11CF-9ABC-0080C7E7B78D}#1.0#0"; "MSWINSCK.OCX"
    Object = "{F9043C88-F6F2-101A-A3C9-08002B2F49FB}#1.2#0"; "COMDLG32.OCX"
    Object = "{6B7E6392-850A-101B-AFC0-4210102A8DA7}#1.2#0"; "COMCTL32.OCX"
    Begin VB.Form frmReceive 
       BorderStyle     =   4  'Fixed ToolWindow
       Caption         =   "Receiving File"
       ClientHeight    =   1665
       ClientLeft      =   45
       ClientTop       =   285
       ClientWidth     =   4980
       LinkTopic       =   "Form1"
       MaxButton       =   0   'False
       MinButton       =   0   'False
       ScaleHeight     =   1665
       ScaleWidth      =   4980
       ShowInTaskbar   =   0   'False
       StartUpPosition =   3  'Windows Default
       Begin MSComDlg.CommonDialog CommonDialog1 
          Left            =   240
          Top             =   1080
          _ExtentX        =   847
          _ExtentY        =   847
          _Version        =   393216
       End
       Begin ComctlLib.ProgressBar ProgressBar1 
          Height          =   435
          Left            =   300
          TabIndex        =   1
          Top             =   240
          Width           =   4395
          _ExtentX        =   7752
          _ExtentY        =   767
          _Version        =   327682
          Appearance      =   1
       End
       Begin VB.CommandButton cancel 
          Caption         =   "Cancel"
          Height          =   435
          Left            =   1800
          TabIndex        =   0
          Top             =   1140
          Width           =   1335
       End
       Begin MSWinsockLib.Winsock sckSystem 
          Left            =   120
          Top             =   600
          _ExtentX        =   741
          _ExtentY        =   741
          _Version        =   393216
          Protocol        =   1
       End
       Begin MSWinsockLib.Winsock sckReceive 
          Left            =   120
          Top             =   120
          _ExtentX        =   741
          _ExtentY        =   741
          _Version        =   393216
       End
       Begin VB.Label compLabel 
          Height          =   255
          Left            =   300
          TabIndex        =   2
          Top             =   780
          Width           =   4395
       End
    End
    Attribute VB_Name = "frmReceive"
    Attribute VB_GlobalNameSpace = False
    Attribute VB_Creatable = False
    Attribute VB_PredeclaredId = True
    Attribute VB_Exposed = False
    'file data
    Public sizeOfFile As Double
    Public sizeOfFileSent As Double
    Public nameOfFile As String
    Public pathToFile As String
    Public userName As String'specify what host to connect to
    Public hostIP As String
    Public hostPort As Double'privates
    Private fileNum As DoublePrivate Sub cancel_Click()sckSystem.SendData CANCEL_TRANSFER
    Unload MeEnd SubPrivate Sub Form_Activate()
    '
    End SubPrivate Sub Form_Initialize()
    '
    End SubPrivate Sub Form_Load()'this defaults port to connect on to 43597 incase it is not set from outside of this form
    If hostPort = 0 Then
        hostPort = 43597
    End If'prepare progress bar
    ProgressBar1.Min = 0
    ProgressBar1.value = ProgressBar1.Min
    ProgressBar1.Visible = True'bind system & send controls together
    'this one is udp
    sckSystem.Close
    sckSystem.RemoteHost = hostIP
    sckSystem.LocalPort = hostPort ' Port to monitor
    sckSystem.RemotePort = hostPort ' Port to connect to.
    sckSystem.Bind'this one is a tcp/ip control
    sckReceive.Close
    sckReceive.LocalPort = hostPort + 1 ' Port to monitor
    sckReceive.ListenEnd SubPrivate Sub sckReceive_Close()    Close fileNum
        MsgBox "Transfer of " & nameOfFile & " completed successfully."
        Unload MeEnd SubPrivate Sub sckReceive_ConnectionRequest(ByVal requestID As Long)    ' Check if the control's State is closed. If not,
        ' close the connection before accepting the new
        ' connection.
        If sckReceive.State <> sckClosed Then sckReceive.Close
        ' Accept the request with the requestID
        ' parameter.
        sckReceive.Accept requestIDEnd SubPrivate Sub sckReceive_DataArrival(ByVal bytesTotal As Long)On Error GoTo ErrorHandler    Dim temp As String
        sckReceive.GetData temp
        Put #fileNum, , temp
        fileLength = LOF(fileNum)
            
        'update progress bar
        sizeOfFileSent = sizeOfFileSent + bytesTotal
        On Error GoTo endIt
        ProgressBar1.value = sizeOfFileSent
        compLabel.Caption = sizeOfFileSent & " of " & sizeOfFile & " sent. " & Int(sizeOfFileSent / sizeOfFile * 100) & "%"
        
        Exit SubErrorHandler:
        MsgBox "An error occured while saving " & CommonDialog1.FileTitle & ". File Transfer being canceled.", vbOKOnly, "IO Error"
        cancel_Click
    endIt:
    End SubPrivate Sub sckSystem_DataArrival(ByVal bytesTotal As Long)Dim temp As String
    sckSystem.GetData temp, vbStringDim command As String, value As String
    command = Mid(temp, 1, 1)
    value = Mid(temp, 2, Len(temp) - 1)Select Case command
        Case FILE_SIZE
            sizeOfFile = value
            'prepare progress bar
            ProgressBar1.Max = sizeOfFile
            queryAcceptDload
        Case USER_NAME
            userName = value
            queryAcceptDload
        Case FILE_NAME
            nameOfFile = value
            Me.Caption = "Receiving " & nameOfFile
            queryAcceptDload
        Case CANCEL_TRANSFER
            stopSending
    '    Case END_TRANSFER
    '        Close fileNum
    '        MsgBox "Transfer of " & nameOfFile & " completed successfully."
    '        Unload Me
    End SelectEnd SubPrivate Sub stopSending()    MsgBox "User has canceled the file transfer.", vbOKOnly, "File Transfer Canceled"
        Unload MeEnd SubPrivate Sub queryAcceptDload()
    CommonDialog1.CancelError = True
    On Error GoTo endIt    If sizeOfFile <> 0 And nameOfFile <> "" And userName <> "" Then
        
            Dim temp
            temp = MsgBox("Would you like to accept " & nameOfFile & " (" & sizeOfFile & " bytes) from " & userName & "?", vbYesNo, "Transfer " & nameOfFile & "?")
            If temp = vbYes Then
                CommonDialog1.ShowSave
                'open the file
                fileNum = FreeFile
                Open CommonDialog1.fileName For Binary Access Write As fileNum
                'tell other end to begin transfer
                sckSystem.SendData ACCEPT_TRANSFER
                            
            Else
                cancel_Click
            End If
            
        End IfExit Sub
    endIt:
    cancel_Click
    End Sub
      

  5.   

    frmSend.frm
    ==============================================================
    VERSION 5.00
    Object = "{248DD890-BB45-11CF-9ABC-0080C7E7B78D}#1.0#0"; "MSWINSCK.OCX"
    Object = "{6B7E6392-850A-101B-AFC0-4210102A8DA7}#1.2#0"; "COMCTL32.OCX"
    Begin VB.Form frmSend 
       BorderStyle     =   4  'Fixed ToolWindow
       Caption         =   "Sending File"
       ClientHeight    =   1665
       ClientLeft      =   45
       ClientTop       =   285
       ClientWidth     =   4980
       LinkTopic       =   "Form1"
       MaxButton       =   0   'False
       MinButton       =   0   'False
       ScaleHeight     =   1665
       ScaleWidth      =   4980
       ShowInTaskbar   =   0   'False
       StartUpPosition =   3  'Windows Default
       Begin ComctlLib.ProgressBar ProgressBar1 
          Height          =   435
          Left            =   300
          TabIndex        =   1
          Top             =   240
          Width           =   4395
          _ExtentX        =   7752
          _ExtentY        =   767
          _Version        =   327682
          Appearance      =   1
       End
       Begin VB.CommandButton cancel 
          Caption         =   "Cancel"
          Height          =   435
          Left            =   1800
          TabIndex        =   0
          Top             =   1140
          Width           =   1335
       End
       Begin MSWinsockLib.Winsock sckSystem 
          Left            =   120
          Top             =   600
          _ExtentX        =   741
          _ExtentY        =   741
          _Version        =   393216
          Protocol        =   1
       End
       Begin MSWinsockLib.Winsock sckSend 
          Left            =   120
          Top             =   120
          _ExtentX        =   741
          _ExtentY        =   741
          _Version        =   393216
       End
       Begin VB.Label compLabel 
          Caption         =   "Waiting For Other Side To Accept Transfer..."
          Height          =   255
          Left            =   300
          TabIndex        =   2
          Top             =   780
          Width           =   4395
       End
    End
    Attribute VB_Name = "frmSend"
    Attribute VB_GlobalNameSpace = False
    Attribute VB_Creatable = False
    Attribute VB_PredeclaredId = True
    Attribute VB_Exposed = False
    'file data
    Public sizeOfFile As Double
    Public sizeOfFileSent As Double
    Public nameOfFile As String
    Public pathToFile As String
    Public userName As String'specify what host to connect to
    Public hostIP As String
    Public hostPort As Double'privates
    Private quitNow As BooleanPrivate Sub cancel_Click()sckSystem.Close
    sckSystem.Bind
    sckSystem.SendData CANCEL_TRANSFER
    Unload Me
    quitNow = TrueEnd SubPrivate Sub Form_Load()'this defaults port to connect on to 43597 incase it is not set from outside of this form
    If hostPort = 0 Then
        hostPort = 43597
    End IfMe.Caption = "Sending " & nameOfFile'find the file size
    sizeOfFile = FileLen(pathToFile)'prepare progress bar
    ProgressBar1.Max = sizeOfFile
    ProgressBar1.Min = 0
    ProgressBar1.value = ProgressBar1.Min
    ProgressBar1.Visible = True'bind sck controls
    sckSystem.Close
    sckSystem.RemoteHost = hostIP
    sckSystem.LocalPort = hostPort ' Port to monitor
    sckSystem.RemotePort = hostPort ' Port to connect to.
    sckSystem.Bind'this one is tcp/ip
    sckSend.RemoteHost = hostIP
    sckSend.RemotePort = hostPort + 1 ' Port to connect to.'send initialization information
    sckSystem.SendData FILE_NAME & nameOfFile
    sckSystem.SendData FILE_SIZE & sizeOfFile
    sckSystem.SendData USER_NAME & userNameEnd SubPrivate Sub sckSystem_DataArrival(ByVal bytesTotal As Long)Dim temp As String
    sckSystem.GetData temp, vbStringDim command As String
    command = Mid(temp, 1, 1)Select Case command
        Case CANCEL_TRANSFER
            stopSending
        Case ACCEPT_TRANSFER
            DoEvents
            sckSend.Connect
            Do Until sckSend.State = sckConnected ' Wait until connected
                DoEvents
            Loop        SendFile pathToFile'        sckSystem.SendData END_TRANSFER
            MsgBox "Transfer Complete"
            Unload Me
            
    End SelectEnd SubPrivate Sub stopSending()
        
        quitNow = True
        MsgBox "User has canceled the file transfer.", vbOKOnly, "File Transfer Canceled"
        Unload MeEnd Sub'*******************************************************************
    ' Credit:       Dan Evans <[email protected]> (with a few mods my me, John Stalcup 6/5/99)
    ' Function:     SendFile()
    ' Purpose:      Send a file via network
    ' Parameters:   Full path and file name of data to send
    ' Returns:      True on success, False on error
    ' Notes:        The socket should already be established
    '*******************************************************************
    Public Function SendFile(fileName As String) As Boolean
            Dim hIn, fileLength, ret
            Dim temp As String
            Dim blockSize As Long
            blockSize = 2048                                '// Set your read buffer size hereOn Error GoTo ErrorHandler        hIn = FreeFile
            Open fileName For Binary Access Read As hIn
            fileLength = LOF(hIn)
            
            Do Until EOF(hIn)
                    ' Adjust blocksize at end so we don't read too much data
                    If fileLength - Loc(hIn) <= blockSize Then
                            blockSize = fileLength - Loc(hIn) + 1
                    End If
                    temp = Space$(blockSize)        '// Allocate the read buffer
                    Get hIn, , temp                 '// Read a block of data
                    ret = DoEvents()                '// Check for cancel button event etc.
                    If quitNow Then Exit Function
                    sckSend.SendData temp           '// Off it goes
                    
                    'update progress bar
                    sizeOfFileSent = sizeOfFileSent + blockSize
                    On Error GoTo endIt             '//
                    ProgressBar1.value = sizeOfFileSent
                    compLabel.Caption = sizeOfFileSent & " of " & sizeOfFile & " sent. " & Int(sizeOfFileSent / sizeOfFile * 100) & "%"
            Loop        sckSend.Close   'this severes the data connection, causing the client to save/end the file        Close hIn
            SendFile = True
            Exit FunctionErrorHandler:                                           '// Always close the file handle
            Close hIn
            SendFile = False
    endIt:
    End Function