Socket Interface

This appendix lists multiple functions from Python’s socket library that can help you get started. You can find more extensive documentation at https://docs.python.org/3/library/socket.html.

socket

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.

import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

connect

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.

host_port = ("127.0.0.1", 4321)
sock.connect(host_port)

send

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.

string_bytes = "Sockets are great!".encode("utf-8")
bytes_len = len(string_bytes)
num_bytes_to_send = bytes_len
while num_bytes_to_send > 0:
    # Sometimes, the operating system cannot send everything immediately.
    # For example, the sending buffer may be full.
    # send returns the number of bytes that were sent.
    num_bytes_to_send -= sock.send(string_bytes[bytes_len-num_bytes_to_send:])

recv

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.

# Waiting until data comes in
# Receive at most 4096 bytes.
data = sock.recv(4096)
if not data:
    print("Socket is closed.")
else:
    print(f"Read data from socket: {data}")

Exceptions

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.

try:
    sock.send("how to handle errors?".encode("utf-8"))
    answer = sock.recv(4096)
except OSError as msg:
    print(msg)

Last updated