VB中的Winsock1发送图片,还原时出错

2025-02-23 21:55:38
推荐回答(1个)
回答1:

这里有个例子,你看看有没有什么启发。

Private Declare Function CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long) As Boolean
Dim bytData() As Byte
Private Sub Command1_Click()
    Winsock1.RemoteHost = Text1.Text
    Dim arr() As Byte
    Dim i As New PropertyBag
    i.WriteProperty "image", Picture1.Picture
    ReDim arr(1 To LenB(i.Contents))
    arr = i.Contents
    If UBound(arr) <= 8192 Then '如果要发送的文件小于数据块大小,直接发送
        Winsock1.SendData arr '发送数据
        Exit Sub
    End If
End Sub

Private Sub Form_Load()
    With Winsock1    '信息发送与接收
        .Protocol = sckUDPProtocol '使用UDP协议
        .RemotePort = 9001 '要连接的端口
        .LocalPort = 9001
        .Bind  '绑定到本地的端口上
    End With
End Sub

Private Sub Form_Unload(Cancel As Integer)
    Erase bytData
End Sub

Private Sub Winsock1_DataArrival(ByVal bytesTotal As Long)
    Dim arr() As Byte
    ReDim arr(1 To bytesTotal)
    Winsock1.GetData arr
    ReDim Preserve bytData(1 To bytesTotal)
    CopyMemory bytData(1), arr(0), bytesTotal
    Dim i As New PropertyBag
    i.Contents = bytData
    Picture2.Picture = i.ReadProperty("image")
End Sub