∟ReverseEchoer.pl - A Simple Socket Server Program
This section provides a tutorial example on how to write a simple socket communication server program, ReverseEchoer.pl, which listens and accepts for any client requests.
The following program called ReverseEchoer.pl is a simple socket communication server application,
which listens for a connection request. Once connected, it
reads what lines of text from the client application, reverses the text lines,
and echoes back to the remote application:
The socket is bound to the local system with the wildcard host address 0.0.0.0,
which represents any IP address on the local host system.
Setting $| to 1 is to turn on auto flush to the default file handle. In order to
turn on auto flush to NEWSOCK, I have to use select() function to switch default file
handles.
If a text line received only contains a single character '.',
the communication link will be terminated by the close() call.
Run ReverseEchoer.pl, you will get the following output on the console window:
Server host: 0.0.0.0
Server port: 8888
This tells us that the program is ready to accept request at address 0.0.0.0
and port 8888.
To test ReverseEchoer.pl, we can use an existing client program called telnet
to initiate the communication request and talk to ReverseEchoer.pl. Open another
command window and type in the following command:
telnet localhost 8888
Immediately, you will see more output on the console window of ReverseEchoer:
Client host: 127.0.0.1
Client port: 1032
This tells us that the server socket received a connection request, and
a communication link has be established with the client application,
which is the telnet program running on the same machine. The client host, 127.0.0.1,
is the standard IP address for "localhost". The client port, 1032, was
picked up by the telnet program.
In the telnet window, type in the following text:
Fish, I love you and respect you very much.
But I will kill you dead before this day ends.
.
The text will be reversed and returned back from the ReverseEchoer.pl:
Welcome to Reverse Echo Server.
.hcum yrev uoy tcepser dna uoy evol I ,hsiF
.sdne yad siht erofeb daed uoy llik lliw I tuB
.
Note that the telnet program is not displaying text you typed in.
It only displays the text received from ReverseEchoer.pl program.