I'm coding an ascynchronous socket client for transferring files (following this Microsoft article) and notice that using BeginReceive corrupts the transfer because it adds a single Null character/chr(0) at the end of each packet. What could be causing this issue? I thought it might be the sending side, but I tested it with SendFile and had the same result.
In the Microsoft article it converts the bytes to an ASCII string and appends it to a StringBuilder. I want to save the bytes on-the-fly, so I barely modified the ReceiveCallback like so:
Private Shared Sub ReceiveCallback(ByVal ar As IAsyncResult)
Dim state As StateObject = CType(ar.AsyncState, StateObject)
Dim client As Socket = state.workSocket
Dim bytesRead As Integer = client.EndReceive(ar)
If bytesRead > 0 Then
FileIO.FileSystem.WriteAllBytes(Application.StartupPath & "\test.exe", state.buffer, True)
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReceiveCallback), state)
Else
receiveDone.Set()
End If
End Sub
The problem is a misconception on how Receive, or BeginReceive & EndReceive work.
When you call Receive and give it a buffer and a size, you are specifying the maximum amount of data to receive. It is the bytesRead that tells you how much you actually received. You need to only write that number of bytes to your output file, as only that portion of your buffer was populated with data.
See here for more details:
http://msdn.microsoft.com/en-us/library/w3xtz6a5
Related
I am writing a program in VB.net that is connecting to a server, sending a byte array to the server and then receives a byte array as an answer then needs to receive a continuous stream of bits from the server.
The Sent Bit Array is 84 bytes and should be the same the first time it is received from the server and vary in size every time the server sends it back after that.
the start and the end of the message will always be the same but the size of the bit array sent will vary.
My issue is that I can write the bits to the server but I am not able to receive any of the follow-on bits that are broadcast.
Any suggestions
Public Sub connect(TcpClient As TcpClient)
Dim NetworkStream As NetworkStream = TcpClient.GetStream()
If networkStream.CanWrite And networkStream.CanRead Then
' Do a simple write.
Dim sendBytes As [Byte]() = IO.File.ReadAllBytes(startupFile)
networkStream.Write(sendBytes, 0, sendBytes.Length)
' Read the NetworkStream into a byte buffer.
Dim bytes(1024) As Byte
NetworkStream.Read(bytes, 0, bytes.Length)
' Output the data received from the host to the console.
Dim returndata As String = Encoding.ASCII.GetString(bytes)
Dim fileWrite As New IO.StreamWriter(writeFile)
fileWrite.Write(returndata)
fileWrite.Close()
Else
If Not networkStream.CanRead Then
Console.WriteLine("cannot not write data to this stream")
TcpClient.Close()
Else
If Not networkStream.CanWrite Then
Console.WriteLine("cannot read data from this stream")
TcpClient.Close()
End If
End If
End If
End Sub
I have the following function to send and receive data it works OK for short strings like 150 bytes, but with a string of 2500 bytes it get stuck.
I tried to send some data with HTWin and nothing get the other end of the net.
So receiver on the other end never get even a character.
I tried also with the old Hyperterminal with same result.
Private Function SendReport(ByVal Msg As String, ByVal Host As String, ByVal Port As String) As String
Try
Dim Tx As New TcpClient()
Dim stream As NetworkStream = Nothing
Dim CloseStream As Boolean = False
Dim LingerMode As New LingerOption(True, 5)
' String to store the response ASCII representation.
Dim responseData As [String] = [String].Empty
Tx.NoDelay = True
Tx.LingerState = LingerMode
Tx.SendTimeout = 10000
Tx.ReceiveTimeout = 10000
Tx.Connect(Host, Port)
' Translate the passed message into ASCII and store it as a Byte array.
Dim data As [Byte]() = System.Text.Encoding.ASCII.GetBytes(Msg)
' Get a client stream for reading and writing.
' Stream stream = client.GetStream();
stream = Tx.GetStream()
CloseStream = True
'stream.WriteTimeout = 100
' Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length)
'Tx.Connected
' Receive the TcpServer.response.
' Buffer to store the response bytes.
data = New [Byte](256) {}
' Read the first batch of the TcpServer response bytes.
Dim bytes As Int32 = stream.Read(data, 0, data.Length)
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes)
If CloseStream = True Then
stream.Close()
End If
Tx.Close()
Return responseData
Catch ex As Exception
WriteRTBLog(ex.Message, Color.Red)
WriteRTBLog(ex.StackTrace, Color.DarkRed)
Return "Error"
End Try
End Function
If I split the big string into smaller one and call this function over and over all the data reach the other end.
Also, I need to get an ACK packet that is big too and the code must wait for and special character that indicates the end.
I was thinking in to create a Thread with a TcpListener but, Is possible to have a TcpListener in the same port of a TcpClient?
The whole idea is to send a big string that is separated by an special character and finished with another special character.
The other end receive the data, split the string using the first special character and send one ACK by every item in the split function.
And in the last ACK send the second special character to indicate the end of the communication, so my application can process the received data properly.
I think I'm drowning in a glass of water.
I have problem about socket to send multiple hex in one send to socket
Here the detail :
Private Sub sendACK()
Dim msgACK As String
Dim sendBytes As Byte()
tmpStr = ""
list.Clear()
msgACK = "33CC"
For j = 1 To Len(msgACK)
list.Add(Mid(msgACK, j, 2))
j += 1
Next
For Each tmpStr In list
sendBytes = HexToBytes(tmpStr)
clientSocket.BeginSend(sendBytes, 0, sendBytes.Length, SocketFlags.None, New System.AsyncCallback(AddressOf OnSend), clientSocket)
Next
End Sub
Public Function HexToBytes(ByVal s As String) As Byte()
Dim bytes As String() = s.Split(" "c)
Dim retval(bytes.Length - 1) As Byte
For ix As Integer = 0 To bytes.Length - 1
retval(ix) = Byte.Parse(bytes(ix), System.Globalization.NumberStyles.HexNumber)
Next
Return retval
End Function
Private Sub OnSend(ByVal ar As IAsyncResult)
clientSocket = ar.AsyncState
clientSocket.EndSend(ar)
Thread.Sleep(100)
End Sub
==> List as arraylist
That code will be result :
Socket send 33
end send
Socket send CC
end send
============================
The program should be sending in one time like this :
Socket send 33 CC
end send
============================
is there any idea about convert string "33CC" into byte and then that program just sending 1 time in outter "for each" ?
thanks for reading and answering....
GBU
Your assumption is incorrect. It does indeed send both bytes at once. You are only calling BeginSend once and you are giving it both bytes, so if it is receiving them at all on the other end, then it is indeed sending them. In fact, there is no difference at all between sending them individually or sending them together. Since the socket works as a stream, the length of time between each byte being sent is largely irrelevant. There will be no way on the receiving end to know whether the two bytes were sent together or separately. All the receiving end will know is that the two bytes were sent in that order. If you think they are being sent as two separate "sends" on the receiving end, it sounds like you are making some invalid assumptions about how to read the data from the socket.
However, I should mention that the way you are sending the bytes, by first creating a hex string and then parsing it, is a bit silly. If you need to parse it as a string, because you are reading the hex values from a text file, or something, that's fine, but otherwise, you should just use hex byte literals in your code rather than strings, for instance:
Dim sendBytes As Byte() = {&H33, &HCC}
I have a tcpclient connection setup capturing a continuous http stream. For some reason after the first few bytes are read, the stream does not get any data for a long time. Is there a problem with my code?
Dim tclient As TcpClient = New TcpClient(url, "80")
nstream = tclient.GetStream()
If nstream.CanRead Then
defaultsize = 8000, BUFFER_SIZE = 1024
Dim bufferread(defaultSize) As Byte
Dim data As String
mstring = New StringBuilder
numbytesread = 0
Dim timestamp As DateTime = DateTime.Now
Do
numbytesread = nstream.Read(bufferread, 0, BUFFER_SIZE)
If numbytesread > 1 Then
timestamp = DateTime.Now
data = Encoding.UTF8.GetString(bufferread, 0, numbytesread)
parsingUtilities.appendXMLtoFile(data)
End If
If DateTime.Now.Subtract(timestamp).TotalSeconds > 60 Then
'timestamp shows no bytesread for more than 60 seconds, then reconnect
Exit Sub
End If
Loop While tclient.Connected
End If
Firstly, you absolutely should not read character data in this way. You're assuming that your byte array always contains a whole number of characters. You should use a StreamReader instead, which is designed to handle this.
If you absolutely must read directly from the stream, use a single instance of Decoder which can handle these partial characters, buffering them for the next conversion.
Now, you're also requiring that numbytesread > 1 - what if it's exactly 1? Why would you want to ignore that?
It's also not clear what your timestamp is for... isn't the stream going to block indefinitely until it gets some data? Or have you explicitly set it up with a read timeout?
Here's the code on the sending side of my sockets:
Private Sub Send(ByRef Buffer() As Byte)
Dim obj_StateObject As New StateObject
obj_StateObject.WorkSocket = m_tmpSocket
m_tmpSocket.BeginSend(Buffer, 0, Buffer.Length, SocketFlags.None, New AsyncCallback(AddressOf OnClientSendComplete), obj_StateObject)
End Sub
Private Sub OnClientSendComplete(ByVal ar As IAsyncResult)
Dim obj_SocketState As StateObject = CType(ar.AsyncState, StateObject)
Dim obj_Socket As Socket = obj_SocketState.WorkSocket
End Sub
Here's the receiving code:
Private Sub OnServerDataArrival(ByVal ar As IAsyncResult)
Dim obj_SocketState As StateObject = CType(ar.AsyncState, StateObject)
Dim obj_Socket As Socket = obj_SocketState.WorkSocket
Dim BytesRead As Integer = obj_Socket.EndReceive(ar)
If (BytesRead > 0) Then
Dim TempLength As Integer = BitConverter.ToInt32(obj_SocketState.Buffer, 0) - 4
Dim TempBuffer(TempLength - 1) As Byte
Array.Copy(obj_SocketState.Buffer, 4, TempBuffer, 0, TempLength)
RaiseEvent ServerDataArrival(TMP_ID, TempBuffer)
End If
obj_Socket.BeginReceive(obj_SocketState.Buffer, 0, obj_SocketState.BufferSize, 0, New AsyncCallback(AddressOf OnServerDataArrival), obj_SocketState)
End Sub
I can send and receive data just fine usually. For instance, I can send a 10 byte buffer across with a button click and there are no problems.
However, if I set that button to call a function that will loop the sending of the 10 byte buffer 10 times, I will not receive about 8 of the buffers on average.
What is causing this? The sending code is executed 10 times, but the OnServerDataArrival function is only executed 2 times.
It is not clear from the code you've provided, but my guess is that you are transmitting the data using TCP (as opposed to UDP). If this is true, you shouldn't expect the send count to match the receive count. If you want that behavior, use UDP instead of TCP.
When using TCP, the data is typically buffered on the send side until a "sufficient" amount of data is ready to be sent. This usually helps improve the overall efficiency of the transmission, especially when sending messages as small as 10 bytes at a time. On the receive side, each read of the TCP socket reads all of the data from the socket's receive buffer up to the size of the buffer you provide. So if 8 of your 10 byte "messages" have been received, the next read from the socket will pull all that data into your buffer (providing it's big enough). You will need to parse your buffer to extract each message from the stream of bytes. Sending the size of the message, as you appear to be doing, will help you do this.