To chat, you need to open a connection over the Internet, which, for the Perl programmer, means dealing with sockets. Until recently this was annoyingly difficult because you had to use pack() to create C structures to pass to low-level system calls. But in the latest versions of Perl, that's all taken care of in the IO::Socket package, so you can open a socket in one step.
When the user connects to the chat server, a telnet program will open a connection to a given port, so the server needs to open a socket on that port and listen for incoming connections. Here's how that's done with
IO::Socket:
use IO::Socket;
my $listening_socket =
IO::Socket::INET->new(Proto => 'tcp',
LocalPort => 2323,
Listen => 1,
Reuse => 1) or die $!;
Here's what the arguments mean:
- Proto: Specifies which network protocol to use - in this case, it's TCP. There
are two main protocols commonly used over the Internet -
TCP and UDP. TCP is for reliable connections and will
resend packets that are lost, while UDP is used in cases
where resending packets isn't useful (such as for
real-time audio).
- LocalPort: Specifies the port number used on this end of the connection.
- Listen: We're listening for connections from other
computers, rather than making a connection ourself. So
a user should telnet to port 2323, on the computer where
our chat server is running, to make a connection.
- Reuse: This socket option means that if we kill the
chat server and restart it, we'll be able to reuse the
port right away, rather than waiting for the previous
session's connections to completely finish.
So now we're listening for someone to connect. When that actually happens, we
need to accept the new connection:
$socket = $listening_socket->accept;
Once we have a connection, we can send some text to the user:
$socket->send("hello\r\n")
or print "connection closed at other end\n";
And we can receive a line of text from the user*:
$socket->recv($line, 80);
if($line eq "") { print "connection closed at other end\n"; }
Finally, when we're done with the connection, we can close it:
$socket->close;
* Not really - see the end of the article.
next page»