Menu

reading *non-terminated* tcp input

Help
2001-07-19
2001-07-23
  • Steve Walters

    Steve Walters - 2001-07-19

    Hello--

    We are using Common C++ on RedHat Linux 7.1 with great success.  My question is:

    What is the best method to receive a "non-terminated" tcp input?  In other words, we want to receive a data stream that may consist of any ASCI character and any length less than 283 bytes.  We do not know the length in advance.

    We have had good results with string input using the getline() function (because we have a terminator), but the read() function blocks until it gets the number of bytes requested.

    Specifically, code in the server is:

        char buf[256];

        memset(buf, 0, 256);
        read(buf, 256);

    If the client sends 36 bytes of data we would like the server to finish reading & fill the first 36 bytes in buf and continue through the code.  If we get at least 256 bytes, no problem.

    Any suggestions are greatly appreciated.

    Steve Walters
    Compass Engineering Group
    7847 Tanners Gate Drive
    Florence, KY  41042
    Tel:    859.525.7899 x108
    Fax:    859.525.7839
    Cell:    513.378.0897

     
    • Nick Liebmann

      Nick Liebmann - 2001-07-19

      I would suggest that you send the number of bytes to be read, as the first 2 bytes of the transfer, or set the socket to timeout after short period of time. The latter will probably be unreliable though, as delays can be introduced for all sorts of reasons, and are rarely consistant!

       
    • Buck

      Buck - 2001-07-22

      Stroutstrup (3/e, section 21.6.4) says there should be a public

      streamsize
      basic_streambuf<stuff,char_traits<stuff>>::in_avail()

      function that tells you how much stuff is in the buffer waiting to be digested, so, depending on whether your standard library sees eye-to-eye with him, i'm guessing you could maybe do something ugly like

      char buf[SIZE];
      read(buf, 1);
      std::streambuf::streamsize n =
         rdbuf()->in_avail();
      if ( n > SIZE - 2 ) n = SIZE - 2;
      read(buf + 1, n);
      buf[1 + n] = '\0';

      although i wouldn't have you quote me on it

       
      • Steve Walters

        Steve Walters - 2001-07-23

        Both suggestions have been very helpful, thanks.  They have taught me more about what the libraries offer.

        Turns out that the packets I am receiving (from an A-B PLC, by the way) contain the packet size in a header that makes using the read() & write() methods *very* handy.

        My apologies to David Sugar; I was bugging him about the read() & write() methods not accepting nulls in the packet -- they do.  It was my test code that didn't.

         

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.