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

(singke) #1

Click here to view code image


import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = ''
port = 5150
server.bind((host, port))
server.listen(5)

The socket() method parameters are somewhat complex, but they’re also somewhat standard. The
AF_INET parameter tells the system that you’re requesting a socket that uses a IPv4 network
address, not an IPv6 network address. The SOCK_STREAM parameter tells the system that you want
a TCP connection instead of a UDP connection. (You use SOCK_DGRAM for a UDP connection.) TCP
connections are more reliable than TCP connections, and you should use them for most network data
transfers.


The bind() function establishes the program’s link to the socket. It requires a tuple value that
represents the host address and port number to listen on. If you bind to an empty host address, the
server listens on all IP addresses assigned to the system (such as the localhost address and the
assigned network IP address). If you need to listen on only one specific address, you can use the
gethostbyaddr() or gethostbyname() method in the socket module to retrieve the
system’s specific host name or address.


Once you bind to the socket, you use the listen() method to start listening for connections. The
program halts at this point, until it receives a connection request. When it detects a connection request
on the TCP port, the system passes it to your program. Your program can then accept it by using the
accept() method, like this:


Click here to view code image


client, addr = server.accept()

The two variables are required because the accept() method returns two values. The first value is
a handle that identifies the connection, and the second value is the address of the remote client. Once
the connection is established, all interaction with the client is done using the client variable. The
two methods you use are send() and recv():


Click here to view code image


client.send(b'Welcome to my server!')
data = client.recv(1024)

The send() method specifies the bytes that you want sent to the client. Note that this is in byte
format and not text format. You can use the standard Python string methods to convert between the text
and byte values. The recv() method specifies the size of the buffer to hold the received data and
returns the data received from the client as bytes instead of a text string value.


When you’re done with the connection, you must close it, like this, to reset the port on the system:


client.close()

Now that you’ve seen the basics, you’re going to create a server program to experiment with.


Try It Yourself: Create a Python Server Program
Follow these steps to create a server program to listen for client connections:
Free download pdf