Warning - This site is moving to https://getthecodingbug.anvil.app
Topics covered
​ Communicating over Local Area Networks (LANs) and the Internet
IP Address
Client-Server applications
Writing our own Client-Server application
Server application
Client application
Running the Server
Running a Client
Communicating over Local Area Networks (LANs) and the Internet
Transmission Control Protocol (TCP) is a standard that defines how to establish and maintain a network conversation via which application programs can exchange data.
TCP works with the Internet Protocol (IP), which defines how computers send packets of data to each other.
Together, TCP and IP are the basic rules defining the Internet.
IP Address
An Internet Protocol address (IP address) is a numerical label assigned to each device connected to a
computer network that uses the Internet Protocol for communication.
When you enter a web address in a browser, it gets translated into an IP address.
The browser then attempts to access the server with that IP address.
For example, if you entered http://www.google.com, it may be translated to say: 216.58.204.26
In most browsers, you can enter the IP address instead,
Client-Server applications
In Computer science, client-server is a software architecture model consisting of two parts, client systems and server systems, both communicating over a computer network or on the same computer.
A client-server application is a distributed system made up of both client and server software.
For example a Chat Server can be made up of two applications, a Client and a Server application.
The Server application runs on one computer and one or more computers can be running the Client application.
Writing our own Client-Server application
We can do this with Python over a LAN. We just need to know the IP address of the computer running the Chat Server application.
Server application
First, we will construct the Server application.
In IDLE create a new program, and save it as chatServer.py, then Copy' n' paste the following code.
# chatServer.py
# This is a server for a chat application
from socket import AF_INET, socket, SOCK_STREAM
from threading import Thread
import time
import socket as sock
# Function to set-up handling for incoming clients
def accept_incoming_connections():
while True:
client, client_address = SERVER.accept()
print(' %s:%s has connected.' % client_address)
client.send(bytes('Greetings - ' + getClientCount(), 'utf8'))
addresses[client] = client_address
Thread(target=handle_client, args=(client,)).start()
# Function to handle a single client connection
def handle_client(client): # Takes client socket as argument.
name = client.recv(BUFSIZ).decode("utf8")
print('Welcoming ' + name + ' to the chat room')
welcome = "Welcome %s! To quit, type 'Quit' to exit.\n" % name
client.send(bytes(welcome, "utf8"))
msg = '%s has joined the chat!' % name
broadcast(bytes(msg, "utf8"))
clients[client] = name
print(getClientCount())
while True:
msg = client.recv(BUFSIZ)
print(' ' + name + ' says: ' + str(msg)[1:])
if 'Quit' not in str(msg):
broadcast(msg, name+": ")
else:
broadcast(msg, name+": ")
client.close()
del clients[client]
broadcast(bytes(' %s has left the chat.' % name, 'utf8'))
print(' %s has left the chat.' % name)
print(getClientCount())
break
return
# Function to report the number of clients
def getClientCount():
clientCount = len(clients)
response = 'There is no one in the chat room'
if clientCount < 1:
return(response)
elif clientCount > 1:
response = 'There are ' + str(clientCount) + ' clients in the chat room'
else:
response = 'There is one client in the chat room'
return(response)
# Function to broadcast a message to all the clients
def broadcast(msg, prefix=''): # prefix is for name identification.
try:
for sock in clients:
sock.send(bytes(prefix, 'utf8') + msg)
except:
pass
# Get local IP
localIP = sock.gethostbyname(sock.gethostname())
print('\nStarting Chat Server on: ' + localIP)
clients = {}
addresses = {}
HOST = ''
PORT = 33000
BUFSIZ = 1024
ADDR = (HOST, PORT)
SERVER = socket(AF_INET, SOCK_STREAM)
SERVER.bind(ADDR)
if __name__ == "__main__":
SERVER.listen(5)
print(getClientCount())
print('Waiting for connections...')
ACCEPT_THREAD = Thread(target=accept_incoming_connections)
ACCEPT_THREAD.start()
ACCEPT_THREAD.join()
SERVER.close()
Running the program should create a database with one table named 'customers'. If the program executed correctly, you should just see 'Finished' printed to the screen and if you look in the same folder you should see a file named 'myDatabase.db'. The 'customers' table is empty, by that, I mean it does not yet have any rows.
Client application
Secondly, we will construct the Server application.
In IDLE create a new program, and save it as chatClient.py, then Copy' n' paste the following code.
# chatClient.py
from socket import AF_INET, socket, SOCK_STREAM
from threading import Thread
import sys
import time
import socket as sock
# Function to handle the reception of messages (running in a separate thread)
def receive():
global connected
while True:
##print('receive heartbeat')
time.sleep(1)
if leaving:
return
try:
msg = client_socket.recv(BUFSIZ).decode("utf8")
if name + ':' not in msg:
print("\n " + msg)
if 'Greetings' in str(msg):
connected = True
except OSError: # Possibly client has left the chat
#print('Exception in receive')
break
return
# Function to handle sending of messages
def send(msg):
client_socket.send(bytes(msg, "utf8"))
# Get local IP
localIP = sock.gethostbyname(sock.gethostname())
print('Your local IP Address is: ' + localIP)
# Get client's name
name = ''
while name == '':
name = input('\nEnter your name: ')
# Get host's name or IP
HOST = input("Enter the IP of the Chat Server: ")
if HOST == '':
HOST = 'localhost'
PORT = 33000
BUFSIZ = 1024
ADDR = (HOST, PORT)
client_socket = socket(AF_INET, SOCK_STREAM)
connected = False
leaving = False
# Connect to server
try:
print('Connecting to: ' + str(ADDR))
client_socket.connect(ADDR)
except Exception as e:
print('Exception: '+ str(e))
print('Could not connect to Chat Server')
sys.exit(1)
# Start thread for reception from server
receive_thread = Thread(target=receive)
receive_thread.start()
try:
# Wait till server welcomes client
print('Waiting for connection')
while not connected:
pass
# Send client's name
send(name)
time.sleep(2)
# Main loop
while True:
msg = input('')
if len(msg) > 0:
send(msg)
if 'Quit' in msg:
print('\nClient closing ...')
client_socket.close()
break
except KeyboardInterrupt:
print('\nClient closing ...')
if connected:
leaving = True
send('Quit')
time.sleep(2)
sys.exit(0)
Running the server
Start the chatServer.py script, by pressing 'F5', if in IDLE.
It will display the IP address of the computer running the server application, so make a note of it.
Running a Client
On another computer you should be able to run the Client application, however, IDLE can get in the way when running this kind of application, so it is better to run it from the command line, i.e. by running CMD.exe.
Start CMD.exe, then in the CMD window, enter:
Python <path-to-your-scripts>\chatClient.py
For example, if you store you Python scripts in M:\User\PythonCourse, then enter:
Python M:\User\PythonCourse\chatClient.py
The application will prompt you for your name, after entering that it will prompt for the Server's IP address.
Enter the address, noted above when starting the Server.
You can now start chatting. When another user starts his/her chatClient.py, in the same way you can have a conversation.
Any time you want to stop your Client application, enter 'Quit' - note it is case-sensitive.
Running the command-line from Python
If it is not possible to run CMD.exe from your Start button, create new python script and save it as runCMD.py, and Copy'n'paste the following code:
# runCMD.py
import os
program = 'cmd.exe'
os.system(program)
Run this, and if you get a CMD window, enter the commands as above.