File: Server.pm

package info (click to toggle)
libtest-unixsock-perl 0.4-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 124 kB
  • sloc: perl: 162; makefile: 2
file content (40 lines) | stat: -rw-r--r-- 796 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package t::Server;
use strict;
use warnings;
use base qw/Exporter/;
use IO::Socket::IP;

our @EXPORT = qw/new_sock/;

sub new_sock {
    my ($host, $port) = @_;
    my $sock = IO::Socket::IP->new(
        LocalPort => $port,
        LocalAddr => $host,
        Proto     => 'tcp',
        Listen    => 5,
        Type      => SOCK_STREAM,
        V6Only    => 1,
        (($^O eq 'MSWin32') ? () : (ReuseAddr => 1)),
    ) or die "Cannot open server socket: $!";
    return $sock;
}

sub new {
    my ($class, $host, $port) = @_;

    my $sock = new_sock($host, $port);
    bless { sock => $sock }, $class;
}

sub run {
    my ($self, $code) = @_;

    while (my $remote = $self->{sock}->accept) {
        while (my $line = <$remote>) {
            $code->($remote, $line);
        }
    }
}

1;