-   Programming (
-   -   very simple perl chat server (

z99 11-22-2012 01:21 PM

very simple perl chat server
i'm new to Perl , i am trying to write a very simple chat server,which will take each client's message and send it back to all other clients,but i'm unable to send the message to other clients,anyway this is my code.any help would be appreciated

use strict;
use IO::Socket;
my $c=0;
my @arr;
sub h {
while(waitpid(-1,WNOHANG)>0) {}
print "server terminated\n";
exit 0;
my $svr=IO::Socket::INET->new(LocalPort=>'12345',Listen=>20,Proto=>'tcp',Reuse=>1) or die 'Cant create Socket';
my $clnt;
while(1) {
next unless $clnt=$svr->accept;
my $child=fork();
my $ip=$clnt->peerhost();
my $port=$clnt->peerport();
print "Connection Aceepted $ip:$port\n";
if($child==0) {
exit 0;
print "$ip:$port Left \n";
sub wc {
my $clnt=shift;
my $msg="$c users(s) online\n";
print $clnt $msg;
sub rcv {
my $ip=$clnt->peerhost();
my $port=$clnt->peerport();
my $c=shift;
while(my $msgin=<$c>) {
print "$ip:$port => $msgin \n";}

linosaurusroot 11-23-2012 05:17 AM


while(1) {
next unless $clnt=$svr->accept;

Each time round this loop you're getting a new connection to a new client in a new process. This is ok for providing independent service to your clients but bad for putting them in communication with each other. In your case you probably want to keep a single process and use select() on multiple sockets.

z99 11-23-2012 06:01 AM

thank you,
for instance,if 5 connection accept then we'll have 5 $clnt ?
how can i have a single process without using select() just with fork().
can we have all the client(s) in an array? like!

while(1) {
next unless $clnt=$svr->accept;
push(@arr,$clnt); <=======
and then pass them to other subs.
is that even right?
thanks in advance

pan64 11-23-2012 06:19 AM

you can keep your clients in an array, that would be ok. But I think you will need to use select otherwise it will be really difficult to implement (or probably impossible)

z99 11-23-2012 06:30 AM

thank you

pan64 11-23-2012 06:38 AM

this is a sample for you:
select is here hidden inside the POE package. You can find several tutorials about it: or ...

All times are GMT -5. The time now is 07:41 AM.