Python Sockets
Introduction
Example
# We need to receive a message of the form
# name=Sergey&last_name=Ivanov&birthday=1990-10-05
# and pull out the first name, last name and birthday
# We use the socket module:
import socket
# Create a socket
sock = socket.socket()
# Choose the host and the port.
# Make the host empty for greater availability
sock.bind(('', 9090))
# Start listening and set the queue size
sock.listen(1)
# Accept a connection with the accept method
# accept returns a tuple with two elements
# the new socket and the client address
# the client address is also a tuple of two elements
# the IP is the element with index 0 (class 'str')
conn, addr = sock.accept()
print('connected:', addr)
client_ip = addr[0]
# In my_list we collect characters four at a time to see
# whether there were two newlines or not
my_list = []
# my_decoded_list is a safety net to make sure
# we did not mistake something else for a newline
# this is not implemented yet
my_decoded_list = []
# i just counts the characters
i = 0
while True:
symbol = conn.recv(1)
# here we should check whether this character decodes at all
# at least wrap it in try
decoded_symbol = symbol.decode('utf-8')
my_list += symbol
my_decoded_list += decoded_symbol
# for now we do not expect a message
# we need to wait for two newlines
message_coming = False
# two newlines caught
if i > 2 and my_list[i] == 10
and my_list[i - 1] == 13
and my_list[i - 2] == 10
and my_list[i - 3] == 13:
# now we wait for the message
message_coming = not message_coming
while message_coming == True:
# the size has to be agreed on in advance
# we wait for up to 2 kilobytes
message = conn.recv(2048)
# Decode from 'b' to 'str'
decoded_message = message.decode('utf-8')
# Check that the message starts with name, otherwise there is no point
# in going on with it
if decoded_message[:5] == 'name=':
# Split by the separator character &
new_list = decoded_message.split('&')
new_list_len = len(new_list)
# Check that there are three elements
if new_list_len == 3:
name = new_list[0][5:]
last_name_check = new_list[1][:9]
if last_name_check == 'last_name':
last_name = new_list[1][10:]
else:
print("Error with last_name name")
message_coming = False
birthday = new_list[2][span class="lightblue">9:span class="lightblue">-2]
print(name)
print(last_name)
print(birthday)
if birthday:
birthday_len = len(birthday)
if birthday_len != 10:
print(f"Error in birthday format. Expected len = 10."
f"Actual len = {birthday_len}")
# Here I send the data back,
# but in general one could call a function and pass arguments
conn.send(bytes(name, 'utf-8'))
conn.send(bytes(last_name, 'utf-8'))
conn.send(bytes(birthday, 'utf-8'))
conn.send(bytes(client_ip, 'utf-8'))
print("OK")
message_coming = False
else:
print(f"message is not full. Expected len = 3."
f"Actual len = {new_list_len}")
message_coming = False
else:
print("message is not of correct format")
message_coming = False
i += 1
if not symbol:
break
# Close the connection
# I have not figured out yet exactly how the connection is closed
conn.close()
Article author: Andrei Olegovich