Hello

Could someone offer some advice on the code below? When I connect a client it connects and does as I would expect. However, it seems to close the socket after the first input from the client.

Is there any way to keep the server running to keep sending/receiving data to/from the client, until the client disconnects?

Ideally I'd like the client to connect, send a 99 and get a corresponding response from the server. Then, the client stays connected and at some point in the future is might send a 63 string or maybe even another 99. All of this without the server closing the connection and forcing the client to reconnect

Thanks!

#!/usr/bin/perl use strict; use warnings; use feature 'say'; use IO::Socket qw(AF_INET AF_UNIX SOCK_STREAM SHUT_WR); use Data::Dumper; my $server = IO::Socket->new( Domain => AF_INET, Type => SOCK_STREAM, Proto => 'tcp', LocalHost => '0.0.0.0', LocalPort => 3333, ReusePort => 1, Listen => 5, ) || die "Can't open socket: $IO::Socket::errstr"; say "Waiting on 3333"; while (1) { my $client = $server->accept(); my $client_address = $client->peerhost(); my $client_port = $client->peerport(); say "Connection from $client_address:$client_port"; my $data; $client->recv($data, 1024); say "received data: $data"; if ($data =~ m/99/) { $data = "We've received a string starting withh 99"; } if ($data =~ m/63/) { $data = "We've received a string starting with 63"; } $client->send($data); }

In reply to IO::Socket simple server by packetstormer

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.