-
Notifications
You must be signed in to change notification settings - Fork 33
/
chat_server.pl
executable file
·120 lines (95 loc) · 2.57 KB
/
chat_server.pl
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
#!/usr/bin/perl
#
## Translation of: https://rosettacode.org/wiki/Chat_server#Python
#
# Create server:
# perl chat_server.pl
# Connect to the chat via telnet:
# telnet localhost 4004
use 5.010;
use strict;
use warnings;
use threads;
use threads::shared;
use IO::Socket::INET;
use Time::HiRes qw(sleep ualarm);
my $HOST = "localhost";
my $PORT = 4004;
my @open;
my %users : shared;
sub broadcast {
my ($id, $message) = @_;
print "$message\n";
foreach my $i (keys %users) {
if ($i != $id) {
$open[$i]->send("$message\n");
}
}
}
sub sign_in {
my ($conn) = @_;
state $id = 0;
threads->new(
sub {
while (1) {
$conn->send("Please enter your name: ");
$conn->recv(my $name, 1024, 0);
if (defined $name) {
$name = unpack('A*', $name);
if (exists $users{$name}) {
$conn->send("Name entered is already in use.\n");
}
elsif ($name ne '') {
$users{$id} = $name;
broadcast($id, "+++ $name arrived +++");
last;
}
}
}
}
);
++$id;
push @open, $conn;
}
my $server = IO::Socket::INET->new(
Timeout => 0,
LocalPort => $PORT,
Proto => "tcp",
LocalAddr => $HOST,
Blocking => 0,
Listen => 1,
Reuse => 1,
);
local $| = 1;
print "Listening on $HOST:$PORT\n";
while (1) {
my ($conn) = $server->accept;
if (defined($conn)) {
sign_in($conn);
}
foreach my $i (keys %users) {
my $conn = $open[$i];
my $message;
eval {
local $SIG{ALRM} = sub { die "alarm\n" };
ualarm(500);
$conn->recv($message, 1024, 0);
ualarm(0);
};
if ($@ eq "alarm\n") {
next;
}
if (defined($message)) {
if ($message ne '') {
$message = unpack('A*', $message);
broadcast($i, "$users{$i}> $message");
}
else {
broadcast($i, "--- $users{$i} leaves ---");
delete $users{$i};
undef $open[$i];
}
}
}
sleep(0.1);
}