pudda has asked for the wisdom of the Perl Monks concerning the following question:
Hello guys,
I'm trying to do a tcp socket server which will send a message to all clients connected every 10s, like a heartbeat.
I managed to do it using IO::Socket::INET only, but the code only handle a single connection, so when the client dies, the server dies too.
Searching, I found a way to do it with IO::Select, but I can't make it work too.
It doesn't send the 'HeartBeat' and still when I stop the a client the server stops too. Can you guys help me to find what I'm doing wrong?
Here the codes:
server.pl
#!/usr/bin/perl -w use strict; use warnings; use IO::Socket; use IO::Select; # auto-flush on socket $| = 1; my $server_ip; my $server_port; ($server_ip,$server_port)=('127.0.0.1', 5000); # creating a listening socket my $tcp_socket = new IO::Socket::INET( LocalHost => $server_ip, LocalPort => $server_port, Proto => 'tcp', Listen => 5, Reuse => 1 ); die "cannot create socket $!\n" unless $tcp_socket; print "server waiting for client connection on port $server_port\n"; my $read_select = IO::Select->new(); $read_select->add($tcp_socket); my $hello ="Hello <VERSION>\n"; while(1){ my $new_readable; my $nick; ($new_readable)=IO::Select->select($read_select,undef,undef,0); foreach my $read(@$new_readable){ if($read==$tcp_socket){ my $new_connection = $read->accept(); $new_connection->send($hello); $read_select->add($new_connection); }else{ my $buf; my $msg; $buf='HeartBeat'; if($buf){ my @sockets = $read_select->can_write(); foreach my $sck(@sockets){ $sck->send("$buf\n"); } }else{ $read_select->remove($read); } } } } $tcp_socket->close();
client.pl
#!/usr/bin/perl #tcpclient.pl use IO::Socket::INET; use CGI; use CGI::Carp qw(fatalsToBrowser warningsToBrowser); $| = 1; my ($socket,$client_socket); $socket = new IO::Socket::INET ( PeerAddr => '127.0.0.1', PeerPort => '5000', Proto => 'tcp' ) or die "ERROR in Socket Creation : $! $@\n"; print "TCP Connection Success.\n"; while(1){ $socket->recv($data,1024); print "Received from Server : $data\n"; } $socket->close();
|
---|
Back to
Seekers of Perl Wisdom