Another version of this video:
Server code:
#server-receive tcp
import socket
#a socket is a pipe that connects to a port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#Address Family_ Internet TCP
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# so we can keep using the same port without waiting (optional)
host = 'localhost' #or 0.0.0.0 when using the real network
port = 3339
s.bind( (host, port) ) #bind to port 3339 because we are receiving
s.listen(1) #the number of allowed pending connections
print('before accept')
conn, addr = s.accept()
#blocking (same as input but instead waits for an incoming connection)
print('after accept')
print('conn = ', conn)
print('addr = ', addr)
data=True
while data:
data = conn.recv(1024)
# also blocking but now for data from the established connection
print(data.decode())
conn.close()
Client code:
#CLIENT-send tcp
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #tcp sock_stream
host = 'localhost' #or localhost if on same machine
port = 3339
s.connect( (host, port) ) # unblocks s.accept on reciever
line = input('Send :') #blocking, waits for user input
s.send(line.encode()) #unblocks conn.recv on receiver
#In tcp connections packets don't have to arrive in order.
#also no guarantee that all data
#is transmitted until connection is closed or use sendall
s.close() #this garantees that all packets are sent