in reply to Chat room with socket programming question

When I run your code, I get a bunch of errors when the client tries to connect. I'm on Windows 7 x64 with Strawberry 5.22.1 64-bit.

It may be just adding the prompt statements in the "if($so == $sock)" block of your server code before accept() call.

This doesn't directly answer your question, but maybe some useful advice? Your code looks a lot like it was ported from C using Socket calls directly. Perl has IO::Socket in core and IO::Socket::IP in newer versions which even allows IPv6 and IPv4 - if you're interested in that.

Following is a simple example TCP client / server with IO::Socket instead. It doesn't use IO::Select so it's blocking, but it seems you have that in your code so you can probably figure out how to incorporate if you need it:

SERVER:

#!/usr/bin/perl use strict; use warnings; use IO::Socket; my $PORT = $ARGV[0] || 7070; $| = 1; my $socket = IO::Socket::INET->new( Proto => "tcp", LocalPort => $PORT, Listen => SOMAXCONN ) || die "Cannot create server\n"; print "TCP Server waiting for client on port $PORT\n"; while (my $client = $socket->accept) { my $peer_addr = $client->peerhost; my $peer_port = $client->peerport; print $client "Welcome to SERVER\n"; print "CONNECTION: ($peer_addr:$peer_port)\n"; while (<$client>) { chomp $_; print "($peer_addr:$peer_port): $_\n"; print $client "$.: $_\n" } close($client); print "DISCONNECT: ($peer_addr:$peer_port)\n"; } die "Cannot accept socket ($!)\n";

CLIENT:

#!/usr/bin/perl use strict; use warnings; use IO::Socket; my $PORT = 7070; if (!$ARGV[0]) { print "Usage: $0 Peer_IPAddress [Port]\n"; exit } elsif ($ARGV[2]) { print "Usage: $0 Peer_IPAddress [Port]\n"; exit } elsif ($ARGV[1]) { $PORT = $ARGV[1] } my $PEER = $ARGV[0]; my $socket = IO::Socket::INET->new( Proto => 'tcp', PeerAddr => $PEER, PeerPort => $PORT ) || die "Cannot create client\n"; #print scalar <$socket>; while (1) { print scalar <$socket>; print "PROMPT> "; my $message = <STDIN>; chomp $message; if (($message !~ /^q(?:uit)?$/i) && ($message !~ /^e(?:xit)?$/i)) +{ print $socket $message . "\n" } else { last } } close($socket);

Replies are listed 'Best First'.
Re^2: Chat room with socket programming question
by Perl_New_Monk (Initiate) on Nov 30, 2016 at 21:21 UTC
    Yes! I was trying to write the feature I wanted but failed. I tested your code.. works perfect, but like you said, it does not have the feature of accepting and rejecting clients.
    I will work more on it and update this post if I find a way to do it.
    Thank you..
      The code you have posted works, but it can only serve one client. I tried connecting a second client but it did not work. I have Windows 7 64 bits and perl 5.22

        Correct. I said it doesn't support that as written. To accept multiple clients, you'll need to add in IO::Select - which I left as your exercise ... your current code has IO::Select in it - should be easy to merge the two.