If I were to do this, I would do it like this:
(Please note that I wrote this code of the top of my head, I did not test any of it)
To send data:
To receive data:vb Code:
Private Sub cmdSendData_Click() Dim DataArr() As String Dim DataStr As String Dim Delimiter As String Dim X As Long ' put the data into an array ReDim DataArr(Hosts.ListCount - 1) For X = 0 To UBound(DataArr) DataArr(K) = Hosts.List(X) Next X ' join all data without a delimiter DataStr = Join(DataArr, "") ' find a character (delimiter) that is NOT used in the data For X = 1 To 254 If InStr(1, DataStr, Chr(X)) = 0 Then Exit For Next X Delimiter = Chr(X) ' join the data using the delimiter, and set it also as first character DataStr = Delimiter & Join(DataArr, Delimiter) ' send the length of the data, following the actual data DataStr = Right("00000000" & Hex(Len(DataStr)), 8) & DataStr ' send the whole thing... Winsock1.SendData DataStr End Sub
vb Code:
Option Explicit Private DataLength As Long, DataBuffer As String Private Sub Winsock1_DataArrival(ByVal bytesTotal As Long) Dim strData As String Winsock1.GetData strData MoreDataToProcess: ' if DataLength = 0, it means this is the start of the data If DataLength = 0 Then ' read the data length, so we know how much to expect DataLength = Val("&H" & Left(strData, 8)) ' save the data into a buffer, excluding the data length DataBuffer = Mid(strData, 9) Else ' append data to the buffer DataBuffer = DataBuffer & strData ' if we received the whole data or more... If Len(DataBuffer) >= DataLength Then ' call the function to process the data Received_All_Data Left(DataBuffer, DataLength) ' if we received more data, process the rest of the data If Len(DataBuffer) > DataLength Then ' read the rest of the data strData = Mid(DataBuffer, DataLength + 1) DataBuffer = "" DataLength = 0 ' jump to the beginning of the function to start the process all over GoTo MoreDataToProcess End If End If End If End Sub Private Sub Received_All_Data(ByVal strData As String) Dim CharDelimiter As String Dim DataLines() As String Dim K As Long ' read the delimiter CharDelimiter = Left(strData, 1) ' split the data by the delimiter (ommiting the first character the delimter) DataLines = Split(Mid(strData, 2), CharDelimiter) ' put the data back into a list List1.Clear For K = 0 To UBound(DataLines) List1.AddItem DataLines(K) Next K End Sub




Reply With Quote