-
-
Save jjasghar/3d291131064f1e68de87fedf1f93f7ea to your computer and use it in GitHub Desktop.
SUPER ADVANCED CHAT SYSTEM USING A SUPER MODEN PROGRAMMING LANGUAGE
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/perl | |
| use strict; | |
| use warnings; | |
| use IO::Socket::INET; | |
| use IO::Select; | |
| # Configuration | |
| my $port = 5000; | |
| # Create a listening socket | |
| my $server = IO::Socket::INET->new( | |
| LocalPort => $port, | |
| Proto => 'tcp', | |
| Listen => 5, | |
| Reuse => 1 | |
| ) or die "Can't start server on port $port: $!"; | |
| print "Listening on port $port...\n"; | |
| my $select = IO::Select->new(); | |
| $select->add($server); | |
| # Store client socket and IP | |
| my %clients; | |
| while (1) { | |
| my @ready = $select->can_read(0.1); | |
| for my $sock (@ready) { | |
| # New connection | |
| if ($sock == $server) { | |
| my $new = $server->accept(); | |
| $new->autoflush(1); | |
| my $ip = $new->peerhost; | |
| $select->add($new); | |
| $clients{$new} = { sock => $new, ip => $ip }; | |
| print "New client connected from $ip\n"; | |
| print $new "Welcome to the Perl Chat! Your IP: $ip\n"; | |
| next; | |
| } | |
| # Existing client sent data | |
| my $line = <$sock>; | |
| if (defined $line) { | |
| chomp $line; | |
| next unless length $line; | |
| my $sender = $clients{$sock}{ip}; | |
| # Broadcast to everyone except sender | |
| for my $client (values %clients) { | |
| next if $client->{sock} == $sock; | |
| print { $client->{sock} } "$sender: $line\n"; | |
| } | |
| # Echo back to sender | |
| print $sock "You said: $line\n"; | |
| } else { | |
| # Client disconnected | |
| my $ip = $clients{$sock}{ip}; | |
| print "Client $ip disconnected\n"; | |
| $select->remove($sock); | |
| delete $clients{$sock}; | |
| close($sock); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment