Last updated
Last updated
This appendix lists multiple functions from Python’s socket library that can help you get started. You can find more extensive documentation at .
You can create a new socket using the socket function. You can use this socket to initiate or respond to a connection request. The parameters specify the network-layer and transportlayer protocol.
Establish a connection using a socket. The parameter is a tuple specifying the network-layer and transport-layer address. The first parameter is a string containing an IP address or a domain name. The second parameter is an integer containing the port number.
send
sends bytes over a socket. Depending on the number of bytes that need to be sent, the available buffer space at the sender, and the number of bytes that can be accepted at the receiver, it may not be possible to send the complete buffer at once. Therefore, the function sends whatever it can and returns the number of bytes it has sent. It is up to the programmer to keep calling send until all bytes are sent.
recv
receives bytes over a socket and returns a buffer containing these bytes. This function is blocking, meaning the function will wait until there are bytes available.
The tests restart your implementations repeatedly using the same IP and port number. To allow the address to be reused, you will probably need to set the SO_REUSEADDR
flag on your socket: yourSocketName.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
Python uses exceptions to handle errors. You can handle errors by placing function calls which can return an error in try-except blocks.