By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,131 Members | 1,749 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,131 IT Pros & Developers. It's quick & easy.

Reading data from a socket: size problem

P: n/a
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_recibi dos)).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) &
"1234567890123456789012345678901234567890123456789 0412345678901234567890123465"

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
--

Regards,

Diego F.

Jun 4 '07 #1
Share this Question
Share on Google+
1 Reply


P: n/a
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.

--

Regards,

Diego F.

Jun 4 '07 #2

This discussion thread is closed

Replies have been disabled for this discussion.