use strict;
use warnings;
use IO::Socket::INET;
use threads;
my $port = 19999;
my $ServerSocket = new IO::Socket::INET (
LocalPort => $port,
Listen => 2,
Type => SOCK_STREAM,
Reuse => 1,
Proto => 'tcp'
);
while (my $clientSocket = $ServerSocket->accept()) {
my $thr = threads->create(\&child_thread, $clientSocket);
}
die "END ServerAccept(), $!";
sub child_thread {
my ($sock) = @_;
print "Accepted client connect\n";
print $sock "Hello client!\n";
chomp(my $from_client = <$sock>);
print "Client says '$from_client'\n";
for (my $i = 0; $i < 5; $i++) {
# Sleep for a while
print "(Still in child thread)\n";
sleep 1;
}
print "(Child thread finishes)\n";
}
####
# Strict
use strict;
use warnings;
# Libraries
use IO::Select;
use IO::Socket;
use Sys::Hostname;
# Outgoing port
my $port = 19999;
my $host = hostname();
my %params = (
'PeerAddr' => $host,
'PeerPort' => $port,
'Proto' => 'tcp',
);
my $sock = new IO::Socket::INET(%params);
$sock or die "Could not create socket ($@)\n";
# Declare succcess connecting
print "\n";
# Read response from server
chomp(my $text = <$sock>);
print "Client gets text '$text'\n";
# Send text to the server
print $sock "Hi Server!\n";
# Wait for a few seconds
sleep 3;
# Close the socket
close($sock);
####
C:\Documents and Settings\liverpole> server
--- Server ---
Accepted client connect
Client says 'Hi Server!
(Still in child thread)
(Still in child thread)
(Still in child thread)
(Still in child thread)
(Still in child thread)
(Child thread finishes)
Accepted client connect
Client says 'Hi Server!
(Still in child thread)
(Still in child thread)
(Still in child thread)
(Still in child thread)
(Still in child thread)
Accepted client connect
Client says 'Hi Server!
(Still in child thread)
(Child thread finishes)
(Still in child thread)
(Still in child thread)
(Still in child thread)
(Still in child thread)
(Child thread finishes)
--- Client ---
C:\Documents and Settings\liverpole> client
Client gets text 'Hello client!'
C:\Documents and Settings\liverpole> client
Client gets text 'Hello client!'
C:\Documents and Settings\liverpole> client
Client gets text 'Hello client!'