Socket code - nonblocking in perl

Posted on 2005-04-05
Last Modified: 2010-03-05

I am writing a script to send a 40 byte header to the server, then the server will respond with 40 bytes of data which I will parse.

This data will be sent to me every 1 second.  This is what I have so far:
#Connect to socket

#Send 40 bytes of data to the server
  my $sock = IO::Socket::INET->new(Proto => 'tcp',
                                   Type  => SOCK_STREAM);
  my $addr = sockaddr_in($port,inet_aton($host));
  my $result = $sock->connect($addr);
#while loop - to get request from server (which will be sent every second)
  #Get data from server    
  print $socket $db
  #Parse this data - store into a file.


I want the connection to remain active even if there is no data passed to the client.
I already have the code to write it to a file.  I guess I am unsure as far as how to keep the connection active...

Question by:jewee
    LVL 18

    Expert Comment

    can't you simply do:

        while($sock->connected) {
            $sock->read($buffer, 40);

    LVL 18

    Expert Comment

    oh, and maybe add a "sleep(1);" line after writing?

    Author Comment

    Maybe i misinterpreted.  I was trying to follow the format of winsock...but yes, that would be much easier!  perl newbie re: the socket programming.

    However, what happens if I do not receive 40 bytes, maybe more?  I guess I could read in 24 bytes (which is the header size), then extract the message size from within there.  How would I access the buffer, as far as extracting the first 4 bytes, checking to see if a bit is set within the 1st 4 bytes, then the 2nd 4 bytes, get the message size?

    I'm not sure as far as how it is stored.  I'm assuming I should use unpack?

    I was told to use nonblocking sockets for this, just to avoid it waiting.

    LVL 18

    Expert Comment

    > However, what happens if I do not receive 40 bytes, maybe more?

    I suppose the remainder will stay in the socket, but I don't know right now how that would affect the following write. Your approach sounds sensible enough, if you have a header that contains the message size.

    > I'm assuming I should use unpack?

    That would be my first suggestion, yes.

    > I was told to use nonblocking sockets for this, just to avoid it waiting.

    That does make sense, although I don't see a particular reason in your code yet why waiting for new data would be so bad.

    Author Comment

    How would i access the buffer?  Thanks!
    LVL 18

    Accepted Solution


        $sock->read($buffer, 24);

    this reads 24 bytes into $buffer. You'd then unpack that according to the layout of your header.

        my ($flags, $size, $rest) = unpack "C4 C4 C16", $buffer;

    (C stands for unsigned char (only does bytes)).

        $flag & 0x02; # test for second bit

    LVL 84

    Assisted Solution

    unpack "C4 C4 C16", $buffer; #unpacks 24 fields of numbers from 0 to 255
    unpack "a4 a4 a16", $buffer; #unpacks 3 string fields with lengths 4, 4, and 16
    unpack "N N a16", $buffer; #unpacks 2  32 bit integers in big-endian order, and a 16 character string


    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    How your wiki can always stay up-to-date

    Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
    - Increase transparency
    - Onboard new hires faster
    - Access from mobile/offline

    Suggested Solutions

    Title # Comments Views Activity
    use perl to insert into MySQL database 9 103
    Perl - Mawk 2 56
    Perl string replace for refred url 9 48
    create a gui in perl 3 20
    Email validation in proper way is  very important validation required in any web pages. This code is self explainable except that Regular Expression which I used for pattern matching. I originally published as a thread on my website : http://www…
    A year or so back I was asked to have a play with MongoDB; within half an hour I had downloaded (,  installed and started the daemon, and had a console window open. After an hour or two of playing at the command …
    Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
    Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…

    779 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    9 Experts available now in Live!

    Get 1:1 Help Now