Hardware Reference
In-Depth Information
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
specified in the channel variable, and finally, 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 modifications, this program could
be used to list the files on an FTP server, or unread emails on a POP3 server.
Receiving data from the socket is a little more complicated. First, you need to create an
empty string variable that will act as the receive buffer, , holding data from the server as it's
received until it can be processed. Initialise the buffer by typing in the following line:
read_buffer = ''
Note that there are two single quotes after the equals sign, not one double quote.
Next, create an empty list, which will be used to store the names of users, by typing the fol-
lowing line:
names = []
The list data type is the same as you used to store the locations in the Raspberry Snake game.
Unlike a normal variable, it can store multiple values—in this case, the names of users pres-
ent in the IRC channel.
The next step is to create an infinite loop, during which the program will continuously query
the server for user names and print them to the screen. Start the loop by typing:
while True:
read_buffer += s.recv(1024)
The first line of the loop, following while True: , tells the socket module to receive 1,024
bytes (1 KB) of data from the IRC server and place it into the read_buffer variable. Because
the += operator is used, rather than just = , the received data will be appended to anything
already in the buffer. The value of 1024 bytes is more or less arbitrary.
The next step is to split the buffer into individual lines of text, using the following program
lines:
lines = read_buffer.split('\r\n')
read_buffer = lines.pop();
Search WWH ::




Custom Search