Python Tutorial - Part 8: Network / Socket Programming
Client1.py
"""
client:
"""
import time
import socket
HOST = '127.0.0.1' # connect to the local host
PORT = 12345 # connect to this port
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT)) # connect to the server
s.sendall(b'Hello world') # send some data to the server
data = s.recv(1024) # recv data
print('From server: ' + repr(data))
time.sleep(5)
## could continue communication
## OR
## look for a delimiter
Server1.py
"""
Server
- can only handle one conection at a time
"""
import socket
#host = '127.0.0.1' # listen on the local host only
#host = 'example.org' # listen on IP that resolves to this host name
host = '' # leave blank to listen on any IP or interface
port = 12345 # above 1023 are non-privileged, 1-65535
s = socket.socket() # open a socket
s.bind((host, port)) # bind to a host and port
s.listen(5) # start listening, optional (in Python py 3.5) backlog number for pending connections
print( "Listening on " + str(host) + ":" + str(port))
while True: # loop for connections ( one at a time )
conn, addr = s.accept() # block and wait for incoming connections
print("Connection from " + str(addr))
while True: # loop to recv data
data = conn.recv(1024) # recv data
if not data: # no more data to recv (socket closed!!)
break # break loop
print("recv: " + str(data))
conn.sendall(data) # send data back
print("Connection closed: " + str(addr))
conn.close() # close connection
Server2.py
"""
Server:
- can handle multiple connections
"""
import socket
from threading import Thread
#host = '127.0.0.1' # listen on the local host only
#host = 'example.org' # listen on IP that resolves to this host name
host = '' # leave blank to listen on any IP or interface
port = 12345 # above 1023 are non-privileged, 1-65535
s = socket.socket() # open a socket
s.bind((host, port)) # bind to a host and port
s.listen(5) # start listening
# optional (in Python 3.5) backlog pending connections
print( "Listening on " + str(host) + ":" + str(port))
def handle_connection(conn):
while True: # loop to recv data
data = conn.recv(1024) # recv data
if not data: # no more data to recv (socket closed!!)
break # break loop
print("recv: " + str(data))
conn.sendall(data) # send data back
print("Connection closed: " + str(addr))
conn.close() # close connection
while True: # loop for connections ( each in a parallel thread )
conn, addr = s.accept() # block and wait for incoming connections
print("Connection from " + str(addr))
t = Thread(target=handle_connection, args=(conn,)) # create a new thread
t.start() # start it
s.close()