Check Packet Size of TCP Data Before Reading Next Byte in Stream

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • quddusaliquddus
    New Member
    • May 2009
    • 23

    Check Packet Size of TCP Data Before Reading Next Byte in Stream

    Hi :D,
    I am sending data to server via TCP IP Connection. I am using a continuous loop at the server end - that accepts new clients and while streams can be read, it reads data stream.

    The data is sent from the client with 2 leading bytes of data that represent the size of the packet of data sent and type of data.

    My question is: how do I retrieve the size of the data packet and then check that this amount of data has been retrieved?

    Thanks :)

    Q

    PS:

    Client:
    Code:
            Dim Enc As Encoding = Encoding.GetEncoding("utf-32")
    
            Dim UserNameText As String = UserName.Text
    
            Dim UserNameTextLength = Enc.GetByteCount(UserNameText)
    
            Dim UserNameByte As Byte() = New Byte(UserNameTextLength + 1) {}
            Enc.GetBytes(UserNameText, 0, UserNameText.Length, UserNameByte, 2)
    
            UserNameByte(0) = 99 'Packet Size
    
            UserNameByte(1) = 88 'Packet Type
    
            Dim Client As New TcpClient("192.168.1.65", 65535)
    
            Dim Stream As NetworkStream = Client.GetStream
    
            Dim Chars As Char() = Enc.GetChars(UserNameByte)
    
            MessageBox.Show(Chars)
    
            Stream.Write(UserNameByte, 0, UserNameByte.Length)
    Server: I would like to retrieve the packet size and then retrieve that size of data.
    Code:
            While Listener.Pending = False
                Client = Listener.AcceptTcpClient()
                Dim Stream As NetworkStream = Client.GetStream()
    
                While Stream.CanRead
    
                    Dim UserNameByte(Client.ReceiveBufferSize) As Byte
                    Stream.Read(UserNameByte, 0, CInt(Client.ReceiveBufferSize))
    
                    Dim UserNameStringByte(Client.ReceiveBufferSize - 2) As Byte
    
                    Array.Copy(UserNameByte, 2, UserNameStringByte, 0, UserNameByte.Length - 2)
    
                    Dim Enc As Encoding = Encoding.GetEncoding("utf-32")
                    Dim Chars As Char() = Enc.GetChars(UserNameStringByte)
    
                    MsgBox(Chars)
    
                End While
    
            End While
  • Plater
    Recognized Expert Expert
    • Apr 2007
    • 7872

    #2
    Assuming your server is at the start of waiting for a message.
    Read in 2 bytes. Convert that into the correct number. Check to see if that many bytes is available to read. Based on that result, either read or continue to wait?

    Comment

    Working...