Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Reading from a socket

Reading from a socket

Scheduled Pinned Locked Moved C#
cssdata-structureshelpquestion
8 Posts 2 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • D Offline
    D Offline
    Diego F
    wrote on last edited by
    #1

    Hello. I have a problem while reading bytes from a socket. According to my test, it seems that the buffer maximum size is 8192 bytes. Then, I use a byte array with that size to read from the buffer. If the send data size is 8192 or less, it works ok. But, if I send more that 8192, let's say 10000 bytes, the first time I read from the buffer I get 8192, and the second, instead of 1808 bytes, it reads 8192 again!!! Isn't the buffer emptied after the reading?

    Regards, Diego F.

    L 1 Reply Last reply
    0
    • D Diego F

      Hello. I have a problem while reading bytes from a socket. According to my test, it seems that the buffer maximum size is 8192 bytes. Then, I use a byte array with that size to read from the buffer. If the send data size is 8192 or less, it works ok. But, if I send more that 8192, let's say 10000 bytes, the first time I read from the buffer I get 8192, and the second, instead of 1808 bytes, it reads 8192 again!!! Isn't the buffer emptied after the reading?

      Regards, Diego F.

      L Offline
      L Offline
      Le centriste
      wrote on last edited by
      #2

      Are you sure of the number of bytes? Maybe you are miscalculating or your call that reads the stream does not move the position to the remaining bytes. Maybe if you can post the code in your loop, we can see what is wrong.

      ----- Formerly MP(2) If atheism is a religion, then not collecting stamps is a hobby. -- Unknown

      D 1 Reply Last reply
      0
      • L Le centriste

        Are you sure of the number of bytes? Maybe you are miscalculating or your call that reads the stream does not move the position to the remaining bytes. Maybe if you can post the code in your loop, we can see what is wrong.

        ----- Formerly MP(2) If atheism is a religion, then not collecting stamps is a hobby. -- Unknown

        D Offline
        D Offline
        Diego F
        wrote on last edited by
        #3

        I send here the code I'm using to test that problem. If I send messages that have a length less that 8192, it works ok. I control the length of the string with the data and the length is what expected. But, if sent data are over 8192, the second time the code enters the loop, the string with result data has 8192 again. 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

        Regards, Diego F.

        L D 3 Replies Last reply
        0
        • D Diego F

          I send here the code I'm using to test that problem. If I send messages that have a length less that 8192, it works ok. I control the length of the string with the data and the length is what expected. But, if sent data are over 8192, the second time the code enters the loop, the string with result data has 8192 again. 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

          Regards, Diego F.

          L Offline
          L Offline
          Le centriste
          wrote on last edited by
          #4

          Hi Diego, First off, this is a C# forum. It is not that I want to be picky, but I hate looking at VB.NET code, it gives me rash. Second, your socket reading code is not familiar to me, but this is not the kind of code I would be using. Use a while this way instead:

          int nbBytesRead;
          while ((nbBytesRead = sock.Receive(bytes_recibidos)) > 0)
          {
          datos_recibidos = (System.Text.Encoding.ASCII.GetString(bytes_recibidos)).TrimEnd(Chr(0))

          ....

          }

          I don't recommend using the Socket.Poll method in a loop. Use it once before the loop, if you want to see if there is data available. Also, you don't need to check for the Socket.Available method, since if Poll returns true, there is data available to read. I don't know what your application does, but if you expect the server to return data immediately after connecting to it, there is no need to Socket.Poll your client socket. Just use the Socket.Receive, which blocks until data is available. If in your application you don't want to wait undefinetely for data, use the following code after creating your socket:

          // The following code will make a Socket.Receive throw a SocketException
          // after 10 seconds with no data coming in.
          sock.ReceiveTimeout = 10000; // 10 seconds (10000 milliseconds)

          Good luck.

          ----- Formerly MP(2) If atheism is a religion, then not collecting stamps is a hobby. -- Unknown

          1 Reply Last reply
          0
          • D Diego F

            I send here the code I'm using to test that problem. If I send messages that have a length less that 8192, it works ok. I control the length of the string with the data and the length is what expected. But, if sent data are over 8192, the second time the code enters the loop, the string with result data has 8192 again. 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

            Regards, Diego F.

            L Offline
            L Offline
            Le centriste
            wrote on last edited by
            #5

            The reason why you always get 8192 bytes is because you don't use the number of bytes returned by the call to Socket.Receive. In my other post, replace the following statement:

            datos_recibidos = (System.Text.Encoding.ASCII.GetString(bytes_recibidos)).TrimEnd(Chr(0));

            with:

            datos_recibidos = (System.Text.Encoding.ASCII.GetString(bytes_recibidos**, 0, nbBytesRead**)).TrimEnd(Chr(0));

            I cannot see the complete code from your while, but in the loop that does not have the complete number of bytes (10000 minus 8192), the call only overwrites the first 1808 bytes in your array, leaving the rest with bytes from the previous read loop. The Encoding.GetBytes method does not copy the string terminating character (\0) in the array of bytes on the server side.

            ----- Formerly MP(2) If atheism is a religion, then not collecting stamps is a hobby. -- Unknown

            D 1 Reply Last reply
            0
            • D Diego F

              I send here the code I'm using to test that problem. If I send messages that have a length less that 8192, it works ok. I control the length of the string with the data and the length is what expected. But, if sent data are over 8192, the second time the code enters the loop, the string with result data has 8192 again. 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

              Regards, Diego F.

              D Offline
              D Offline
              Diego F
              wrote on last edited by
              #6

              First of all, my excuses for posting here. This should be in VB.NET subforum. Anyway, I found the mistake. When I do sock.Receive, the array isn't cleared. I didn't expected that, but if I read 100 bytes and the time before it was 150 bytes, the last 50 bytes are from the first time. So I used the Array.Clear method and I avoid that problem.

              Regards, Diego F.

              L 1 Reply Last reply
              0
              • D Diego F

                First of all, my excuses for posting here. This should be in VB.NET subforum. Anyway, I found the mistake. When I do sock.Receive, the array isn't cleared. I didn't expected that, but if I read 100 bytes and the time before it was 150 bytes, the last 50 bytes are from the first time. So I used the Array.Clear method and I avoid that problem.

                Regards, Diego F.

                L Offline
                L Offline
                Le centriste
                wrote on last edited by
                #7

                Diego, it is not the right way to do it. Use the value returned by Socket.Receive to know how many bytes are read. Read my 2 other replies to your post (the one you show the code used).

                ----- Formerly MP(2) If atheism is a religion, then not collecting stamps is a hobby. -- Unknown

                1 Reply Last reply
                0
                • L Le centriste

                  The reason why you always get 8192 bytes is because you don't use the number of bytes returned by the call to Socket.Receive. In my other post, replace the following statement:

                  datos_recibidos = (System.Text.Encoding.ASCII.GetString(bytes_recibidos)).TrimEnd(Chr(0));

                  with:

                  datos_recibidos = (System.Text.Encoding.ASCII.GetString(bytes_recibidos**, 0, nbBytesRead**)).TrimEnd(Chr(0));

                  I cannot see the complete code from your while, but in the loop that does not have the complete number of bytes (10000 minus 8192), the call only overwrites the first 1808 bytes in your array, leaving the rest with bytes from the previous read loop. The Encoding.GetBytes method does not copy the string terminating character (\0) in the array of bytes on the server side.

                  ----- Formerly MP(2) If atheism is a religion, then not collecting stamps is a hobby. -- Unknown

                  D Offline
                  D Offline
                  Diego F
                  wrote on last edited by
                  #8

                  Ok, I did change it. Thank you for your advise.

                  Regards, Diego F.

                  1 Reply Last reply
                  0
                  Reply
                  • Reply as topic
                  Log in to reply
                  • Oldest to Newest
                  • Newest to Oldest
                  • Most Votes


                  • Login

                  • Don't have an account? Register

                  • Login or register to search.
                  • First post
                    Last post
                  0
                  • Categories
                  • Recent
                  • Tags
                  • Popular
                  • World
                  • Users
                  • Groups