Re: Visual Basic General Tcp receive acting strange
meriano
I apologize my last post was not really clear. I do know and send the number of bytes in the socket.BeginSend() method but I am not sure how to receive only that number of bytes on the receiver. The number of bytes is variable so I know I cannot hard code the receive buffer size, but how do you only receive a specific number of bytes.
Sending code
Public Sub Send(ByVal dataToSend As String)
Try
bytesToSend() As Byte = System.Text.ASCIIEncoding.ASCII.GetBytes(dataToSend)
mysocket.Send(bytesToSend,0,bytesToSend.Length)
Catch se as SocketException
MsgBox(se.ToString)
End Try
End Sub
Receiving
Private Class StateClass
Public clientSocket As Socket
Public clientBuffer() As Byte ------> how do i know the buffer size before hand
End Sub
Public Sub OnAcceptConnection(ByVal result as IAsyncResult)
Dim state as New stateClass
Dim serverSocket As Socket = CType(result.AsyncState, Socket)
Try
state.clientSocket = serverSocet.EndAccept(result)
state.clientSocket.BeginReceive(state.clientBuffer,0,state.clientBuffer.Length,SocketFlags.None, _
New AsyncCallback(AddressOf ReceiveCallback,stateClass)
Catch acceptex as Exception
MsgBox(acceptex.ToString)
EndTry
EndSub
Private ReceiveCallback(ByVal result2 as IAsyncResult)
Try
Dim state As stateClass,CType(result2.AyncState,stateClass)
Dim numberBytesRead As Int32 = state.clientSocket.EndReceive(result2)
If numberBytesRead >0 Then
Dim receivedString As String = ASCII.GetString(state.clientBuffer)
Console.WriteLine(receivedString)
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub