LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   very simple perl chat server (https://www.linuxquestions.org/questions/programming-9/very-simple-perl-chat-server-4175438319/)

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
Code:

use strict;
use IO::Socket;
use POSIX 'WNOHANG';
my $c=0;
my @arr;
$SIG{CHLD}=\&h;
sub h {
while(waitpid(-1,WNOHANG)>0) {}
};
$SIG{'INT'}=sub 
{
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;
$c++;
#push(@arr,$clnt);
my $child=fork();
my $ip=$clnt->peerhost();
my $port=$clnt->peerport();
print "Connection Aceepted $ip:$port\n";
if($child==0) {
$svr->close;
wc($clnt);
exit 0;
print "$ip:$port Left \n";
}
$clnt->close;
}
 
sub wc {
my $clnt=shift;
my $msg="$c users(s) online\n";
print $clnt $msg;
rcv($clnt);
}
 
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

Code:

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!
Quote:

while(1) {
next unless $clnt=$svr->accept;
$c++;
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: http://poe.perl.org/?POE_Cookbook/Chat_Server
select is here hidden inside the POE package. You can find several tutorials about it: http://www.nntp.perl.org/group/perl....msg113832.html or ...


All times are GMT -5. The time now is 04:29 PM.