Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1

  1. Create the script2003.py program in the folder for this hour.

  2. Open the script2003.py file with a text editor and enter the code shown here:
    Click here to view code image
    1: #!/usr/bin/python3
    2:
    3: import socket
    4: server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    5: host = ''
    6: port = 5150
    7: server.bind((host, port))
    8: server.listen(5)
    9: print('Listening for a client...')
    10: client, addr = server.accept()
    11: print('Accepted connection from:', addr)
    12: client.send(str.encode('Welcome to my server!'))
    13: while True:
    14: data = client.recv(1024)
    15: if (bytes.decode(data) == 'exit'):
    16: break
    17: else:
    18: print('Received data from client:', bytes.decode(data))
    19: client.send(data)
    20: print('Ending the connection')
    21: client.send(str.encode('exit'))
    22: client.close()

  3. Save the file.


The script2003.py program goes through the steps to bind to a socket on the local system (line
7) and listen for connections on TCP port 5150 (line 8). When it receives a connection from a client
(line 10), it prints a message in the command prompt and then sends a welcome message to the client
(lines 11 and 12). This example uses the str.encode() string method to convert the text into a
byte value to send and the bytes.decode() method to convert the bytes into text values to
display.


After sending the welcoming message, the code goes into an endless loop, listening for data from the
client and then returning the same data (lines 13 through 19). If the data is the word exit, the code
breaks out of the loop and closes the connection.


That’s it for the server side! Now you’re ready to work on the client side of the application.


Creating the Client Program


The client side of a network connection is a little simpler than the server side. It simply needs to
know the host address and the port number that the server uses to listen for connections, and then it
can create the connection and follow the protocol that you created to send and receive data.


Just like a server program, a client program needs to use the socket() method to establish a socket
that defines the communication type. Unlike the server program, it doesn’t need to bind to a specific
port; the system will assign one to it automatically to establish the connection. With that, you just need
five lines of code to establish the connection to the server:


Click here to view code image


import socket
Free download pdf