Reading data from a socket: size problem

D

Diego F.

Hello. I'm having problems reading data from a socket. In my test, I see the
maximum size to get data from the socket is 8192 bytes.

In my tests, if I send less that 8192, the readen data have the expected
size. But, if I send more than 8192, my code has a loop, and the second time
it reads from the socket, it reads 8192 bytes again, instead that only the
bytes not read before.

I hope you can understand the problem. Here is some code that I use to test
this:

This is the client code:

Dim bytes_recibidos(8192) As Byte
Dim datos_recibidos As String

Dim p As New IPEndPoint(IPAddress.Parse("127.0.0.1"), 870)
sock = New Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp)

Try
sock.Connect(p)
ListBox1.Items.Add("Conectado")

Dim socket_conectado As Boolean = True
While (socket_conectado)
If (sock.Poll(0, SelectMode.SelectRead) And (sock.Available = 0)) Then
socket_conectado = False
End If

sock.Receive(bytes_recibidos)
datos_recibidos =
(System.Text.Encoding.ASCII.GetString(bytes_recibidos)).TrimEnd(Chr(0))
....
End While

Catch ex As Exception

End Try

And the server code to test that problem:


Dim server As TcpListener
server = Nothing
Try

server = New TcpListener(IPAddress.Parse("127.0.0.1"), 870)
ListBox1.Items.Add("Esperando conexiones...")
server.Start()

Dim cliente As TcpClient = server.AcceptTcpClient()

Dim stream As NetworkStream = cliente.GetStream()
Dim bytes_enviados(8192) As Byte
For i As Integer = 1 To 106

Dim cmd As String = Chr(0) &
"12345678901234567890123456789012345678901234567890412345678901234567890123465"

bytes_enviados = System.Text.Encoding.ASCII.GetBytes(cmd)
stream.Write(bytes_enviados, 0, bytes_enviados.Length)
Next
Catch ex As SocketException

Finally
server.Stop()
End Try
 
D

Diego F.

I solved it by adding this line before reading from the socket:
Array.Clear(bytes_recibidos, 0, bytes_recibidos.Length)

I expected the array to be cleared itself, but I have to do it manually.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top