Hardware Reference
In-Depth Information
Next, you need to tell the program to try connecting to the IRC server speciied in the vari-
ables at the start of the program. Type the following lines:
print 'Connecting to %(host)s:%(port)s...' % irc
try:
s.connect((irc['host'], irc['port']))
except socket.error:
print 'Error connecting to IRC server Æ
%(host)s:%(port)s' % irc
sys.exit(1)
he try and except commands are included in this code for error handling . If the system
fails to connect to the server—because the Pi isn't connected to the Internet, for example, or
because the server is down for maintenance—the program will print an error message and
gracefully exit. he s.connect line tells the socket module to try connecting to the IRC
server, using the host and port variables held in the irc dict.
If the program doesn't quit from the exception, it has successfully connected to the IRC
server. Before you can get a list of names in a channel, however, you need to identify yourself
to the server and issue some commands using the send function of the socket module.
Type the following lines into the program:
s.send('NICK %(nick)s\r\n' % user)
s.send('USER %(username)s %(hostname)s Æ
%(servername)s :%(realname)s\r\n' % user)
s.send('JOIN %(channel)s\r\n' % irc)
s.send('NAMES %(channel)s\r\n' % irc)
he send function works in almost exactly the same way as the print function, except that
instead of printing to the standard output—usually the terminal window or console—it
sends the output through the network connection. In this case, the program is sending
strings of text to the IRC server and telling it to register the program using the nickname
held in the nick variable and the user details held in the username , hostname , server-
name and realname variables. Next, the program sends the command to join the channel
speciied in the channel variable, and inally, it sends the command to receive the list of
users in that channel. Although this example is tailored to IRC, the same basic principle can
be used to issue commands to any network service—with modiications, this program could
be used to list the iles on an FTP server, or unread emails on a POP3 server.
Search WWH ::




Custom Search