SlideShare a Scribd company logo
Tutorial 3 : Networking with
Python| Learning Python on the
Go....
1
IoT – Basic Idea
2
Recall :
Interfacing sensors to the computing unit
Source: Book website: http://www.internet-of-things-book.com
Raspberry Pi
Breadboard
Jumper wires
Electrical
components
Sensors
3
Vehicular Language : Python
Installation, Guide, Docs....
www.python.org
4
Recall : Programming the Raspberry Pi
Learning Python on the Go.......
The latest version of Raspbian includes the RPI.GPIO Python library pre-installed,
so you can simply import that into your Python code. The RPI.GPIO is a library that allows your Python application to easily
access the GPIO pins on your Raspberry Pi. The as keyword in Python allows you to refer to the RPI.GPIO library using the
shorter name of GPIO. There are two ways to refer to the pins on the GPIO: either by physical pin numbers (starting from pin 1 to
40 on the Raspberry Pi 2/3), or Broadcom GPIO numbers (BCM)
Module import
GPIO pin setup
Execute in loop
Send a HIGH signal to pin 18
Wait for 1 time unit
Send a LOW signal to pin 18
Wait for 1 time unit
Python program which instructs the Rpi to blink
a LED - turn the LED high and low alternately
5
Interfacing Rpi to DHT11
Using the Adafruit DHT 11 library
1. git clone https://github.com/adafruit/Adafruit_Python_DHT.git
2. cd Adafruit_Python_DHT
3. sudo apt-get install build-essential python-dev
4. sudo python setup.py install
Python program that instructs the
Rpi to read data from the DHT11
module and print it
6
The Four Layered IoT Architecture
Source : ITU-T
Focus of this
tutorial
7
IoT Protocol Stack
Source : Internet
8
Task : An application reads sequence of data
inputs via some wireless protocol ex. Bluetooth
1. Start – Start receiving data
2. Acknowledgment – send acknowledgement about the last data packet
3. Data – sensing node sends data packet containing displacement and orientation information
4. Stop – stop processing in the sensing node
Sensing Node
(accelerometer)
Commands :
START, Data, STOP
dx
dy
dz
da
Computation
Displacement (x,y,z)
64 bit data over
Bluetooth
Acknowledgement
Application
9
Flow Chart showing Data Transfer
begin
Connect to the
sensor node
Send START
command to
sensor node
Received n
inputs?
Send STOP to
sensor node
end
Yes
No
receive data from
sensor node
Send Acknowledgement
to sensor node
10
Flow Chart showing Data Transfer
Step 1 : Initialization
begin
Connect to the
sensor node
Send START
command to
sensor node
Received n
inputs?
Send STOP to
sensor node
end
Yes
No
receive data from
sensor node
device = 'COM3'
baudrate = 115200
Btserial =
open_device(devic
e,baudrate)
Send Acknowledgement
to sensor node
11
Flow Chart showing Data Transfer
Step 2 : setting up the sensor node – send cmd
begin
Connect to the
sensor node
Send START
command to
sensor node
Received n
inputs?
Send STOP to
sensor node
end
Yes
No
receive data from
sensor node
device = 'COM3'
baudrate = 115200
Btserial = open_device(device,baudrate)
#write command to start interaction with
the sensor node
cmd = START
write_device(btserial,cmd)
Send Acknowledgement
to sensor node
cmd = header, payload,checksum
Header is a single byte command ID
Payloads could be multiple bytes command
Last two bytes in any command are
checksum.
12
Flow Chart showing Data Transfer
Step 3 : Check the number of packets received
begin
Connect to the
sensor node
Send START
command to
sensor node
Received n
inputs?
Send STOP to
sensor node
end
Yes
No
receive data from
sensor node
#read data and understand it
pkt_len, num_rcvd = 64, 0
while (num_rcvd < 200):
buffer = read_device(btserial,
pkt_len)
…
#Send the ack to sensor
node
…
#do processing of the
payload
…
num_rcvd += 1
Send Acknowledgement
to sensor node
def read_device(device,length):
buffer = [ ]
device.flushInput()
buffer = device.read(length)
return buffer
13
Flow Chart showing Data Transfer
Step 4 : Receive data packets from sensor node
begin
Connect to the
sensor node
Send START
command to
sensor node
Received n
inputs?
Send STOP to
sensor node
end
Yes
No
receive data from
sensor node
#read data and understand it
pkt_len = 64
buffer = read_device(btserial,
pkt_len)
valid,packet_info,payload =
parse_pkt(buffer)
if (valid == False):
continue
#do something with the info
and payload
Send Acknowledgement
to sensor node
14
Flow Chart showing Data Transfer
Step 5 : Acknowledgement sent to sensor node
begin
Connect to the
sensor node
Send START
command to
sensor node
Received n
inputs?
Send STOP to
sensor node
end
Send Acknowledgement
Yes
No
receive data from
sensor node
#read data and understand it
pkt_len = 64
buffer = read_device(btserial, pkt_len)
valid,packet_info,payload =
parse_pkt(buffer)
if (valid == False):
continue
#do something with the info and payload
to sensor node
Internet of Things
Instructor : Dr. Bibhas Ghoshal
#read data and understand it
pkt_len = 64
buffer =
read_device(btserial,
pkt_len)
valid,packet_info,payload = parse_pkt(buffer)
if (valid == False): continue
#Send the ack to the sensor node
ack=create_ack(packet_info)
write_device(btserial, ack)
#do processing of the payload
15
Flow Chart showing Data Transfer
Step 6 : Send STOP command to the node
begin
Connect to the
sensor node
Send START
command to
sensor node
Received n
inputs?
Send STOP to
sensor node
end
Send Acknowledgement
Yes
No
receive data from
sensor node
device = 'COM3'
baudrate = 115200
Btserial = open_device(device,baudrate)
#write command to start interaction with
the sensor node
cmd = START
write_device(bt
serial,cmd)
#stop interacting with the sensor
node cmd = STOP
write_device(btserial,cmd)
to sensor node
16
Sockets
Socket is a software object that acts as an end point of a bidirectional communication link between
server and client programs on network
Support in the operating system allows to implement clients and servers for both TCP and UDP
communication.
Python provides network service for server-client model.
Python has additionally libraries which allow higher access to specific application level network
protocols
socket()
connect()
send()
receive()
close()
send()
socket()
bind()
listen()
accept()
receive()
Connection
Established
request
response
C
L
I
E
N
T
S
E
R
V
E
R
Socket Programming (TCP)
17
Sockets
Socket is a software object that acts as an end point of a bidirectional communication link between server and
client programs on network
Sockets have two primary properties controlling the way they send data: the address family controls the OSI
network layer protocol used and the socket type controls the transport layer protocol.
Support in the operating system allows to implement clients and servers for both TCP and UDP communication.
Python provides network service for server-client model.
Python has additionally libraries which allow higher access to specific application level network protocols
socket()
bind()
send to ()
rcvfrom () sendto()
socket()
bind()
rcvfrom ()
request
response
C
L
I
E
N
T
S
E
R
V
E
R
Socket Programming (UDP)
18
Ports
Port is a number to identify the sender or receiver of message.
Each host has 65,536 ports
Ports 0-1023 are reserved.
Protocol Port # Protocol Port #
FTP 20 SMTP 25
SSH 22 HTTP 80
TELNET 23 HTTPS 443
Ports above 1024 are reserved for user processes.
Socket must bound to port n server.
19
Creating a Socket
Getting Host Information
gethostbyname(hostname) : Provide the IP address associated with a
hostname
gethostbyname_ex(hostname)
>>> import socket
>>>
socket.gethostbyname('localhost')
'127.0.0.1’
socket(family, type): Opens a socket, family is one of
AF_UNIX or AF_INET
type is one of SOCK_DGRAM or
SOCK_STREAM
# TCP socket
S =
socket.socket(socket.AF_INET,socket.SOCK
20
Useful Functions on Socket
accept() : accept a connection, returning new socket and client
address
bind(addr) : bind the socket to a local address
close() : close the socket
connect(addr) : connect the socket to a remote address
listen(n) : start listening for incoming connections
recv(buflen[, flags]) : receive data
send(data[, flags]) : send data, may not send all
of it
21
TCP Server
The socket module
Provides access to low-level network programming functions.
Example: A server that receives data and sends ack
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # TCP
socket # Bind to local ip and port 8888
# Start listening, hold upto 5 connections
s.bind(("",8888))
s.listen(5)
while 1:
client, addr = s.accept() # Wait for a connection
print "Got a connection from ", addr
data = client.recv(1024 # receive client's data upto 1024 byte
print "Received data from client:", data
client.send("Acknowledgement for received data") # Send ack back
client.close()
22
TCP Client
The Client Program Connects to server, sends data and waits
for ack
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Create TCP socket
s.connect(("127.0.0.1",8888))# Connect to server
s.send("Hello Server..")
msg = s.recv(1024)
s.close()
# Send message to server
# Receive up to 1024 bytes
# Close connection
print "Server's message:", msg
23
Problems with the TCP Server
Lots of repetitive coding
Not really handling multiple (concurrent) clients
Clients are queued
Handled in sequential way
Real world server would need concurrency
Even more coding!
24
Socket Server
Python module to simplify creation of realistic servers
Functionality to support basic network services such as HTTP, SMTP
from help(SocketServer)
Supports various server classes:
TCPServer(address, handler)
UDPServer(address, handler)
ForkingTCPServer(address, handler)
ForkingUDPServer(address, handler)
ThreadingTCPServer(address, handler)
ThreadingUDPServer(address, handler)
Need to define request handler, Derive from BaseRequestHandler class
Minimum requirement: define handle() method
handle()called each time a connection request is received
25
Useful Python Modules for Networking
ftplib - for connecting to a ftp server
smtplib - for sending emails
urllib - To download contents of a URL
httplib - communication over HTTP
poplib/imaplib - email access protocols
JavaScript Object Notation (JSON) –
read and write data interchange format
Tw
o
str
uc
tur
es
– i.
col
lec
tio
n
of
na
m
e,
26
Example of a JSON and XML Format
JSON Format
{"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value":
"New",
"onclick":
"CreateNewDo
c()"},
{"value":
"Open",
"onclick":
"OpenDoc()"}
,
{"value":
"Close",
"onclick":
"CloseDoc()"
}
]
}
}}
The same text 27
Encoding and Ecoding JSON in Python
import json
# A basic python dictionary
py_object = {"c": 0, "b": 0, "a": 0}
# Encoding
json_string = json.dumps(py_object)
print(json_string)
print(type(json_string))
# Decoding JSON
py_obj = json.loads(json_string)
print()
print(py_obj)
print(type(py_obj))
Output:
{"c": 0, "b": 0, "a": 0}
<class 'str'>
{'c': 0, 'b': 0, 'a': 0}
<class 'dict'>
28
GET and POST requests in Python
29
GET requests in Python
# importing the requests library
import requests
# api-endpoint
URL = "http://maps.googleapis.com/maps/api/geocode/json"
# location given here
location = "iiita"
# defining a params dict for the parameters to be sent to the
API
PARAMS = {'address':location}
# sending get request and saving the response as response
object
r = requests.get(url = URL, params = PARAMS)
# extracting data in json format
data = r.json()
# extracting latitude, longitude and formatted
address # of the first matching location
latitude = data['results'][0]['geometry']['location']
['lat']
longitude = data['results'][0]['geometry']['location']['lng']
formatted_address = data['results'][0]['formatted_address']
# printing the output
print("Latitude:%snLongitude:%snFormatted Address:%s
%(latitude, longitude,formatted_address)) 30
POST requests in Python
# importing the requests library
import requests
# defining the api-endpoint
API_ENDPOINT = "http://pastebin.com/api/api_post.php"
# your API key here
API_KEY = "XXXXXXXXXXXXXXXXX"
# your source code here
source_code = '''
print("Hello, world!")
a = 1
b = 2
print(a + b)
'''
# data to
be sent to
api
data = {'api_dev_key':API_KEY,
'api_option':'paste',
'api_paste_code':source_code,
'api_paste_format':'python'}
# sending post request and saving response as response object
r = requests.post(url = API_ENDPOINT, data = data)
# extracting response text
pastebin_url = r.text
print("The pastebin URL
is:%s"%pastebin_url)
31

More Related Content

PPTX
EN-04 (1).pptx
PPTX
Unit V computer network notes for study.
PPT
Sockets
PPTX
Raspberry pi Part 23
PPTX
5-LEC- 5.pptxTransport Layer. Transport Layer Protocols
PPT
Unit 8 Java
PDF
JavaSockets-Session10 New York university.pdf
PPT
Network programming in Java
EN-04 (1).pptx
Unit V computer network notes for study.
Sockets
Raspberry pi Part 23
5-LEC- 5.pptxTransport Layer. Transport Layer Protocols
Unit 8 Java
JavaSockets-Session10 New York university.pdf
Network programming in Java

Similar to 5-Tut3_Networking_with_Python.pptx good intro (20)

PPTX
Socket programming
PPTX
13_TCP_Attack.pptx
PPT
Network Programming in Java
PDF
Osi model
PPT
Network programming in Java
PPTX
PPTX
Networking in Java
PPT
2-CN_UDP_TCP_f7a922763a77c5ea2bc334f8e36c71f8.ppt
PPTX
Week4 lec1-bscs1
PPT
Chapter3.ppt hu yyttujhgft uhhgfrghbhhgghhjhy
PPTX
Chuong5_Networking_updated.Networking_updatedpptx
PPT
Sockets
PDF
Socket Programming
PPT
More on Tcp/Ip
PPT
CHAT SERVER
PDF
Socket programming using C
PPT
Lecture1, TCP/IP
PPTX
#KPC #CST #Protocols
ODP
Your app lives on the network - networking for web developers
PPT
Socket programming in C
Socket programming
13_TCP_Attack.pptx
Network Programming in Java
Osi model
Network programming in Java
Networking in Java
2-CN_UDP_TCP_f7a922763a77c5ea2bc334f8e36c71f8.ppt
Week4 lec1-bscs1
Chapter3.ppt hu yyttujhgft uhhgfrghbhhgghhjhy
Chuong5_Networking_updated.Networking_updatedpptx
Sockets
Socket Programming
More on Tcp/Ip
CHAT SERVER
Socket programming using C
Lecture1, TCP/IP
#KPC #CST #Protocols
Your app lives on the network - networking for web developers
Socket programming in C
Ad

More from ssuser0b643d (7)

PPTX
3-Tut2_Interfacing_Sensors_RPioT.pptx good reference
PPTX
iot-application-layer-protocols-v1-200125143512.pptx
PPTX
Lecture3_IoT_System_Design_Methodology-Ch1.pptx
PDF
S&D PPTs sensors and devices presentation
PPTX
FIOT_Unit_2 (1)softwaredefinedradio.pptx
PPTX
FIot_Unit-3 fundAMENTALS OF IOT BASICS.pptx
PPTX
fundamentals of iot cloud computing.pptx
3-Tut2_Interfacing_Sensors_RPioT.pptx good reference
iot-application-layer-protocols-v1-200125143512.pptx
Lecture3_IoT_System_Design_Methodology-Ch1.pptx
S&D PPTs sensors and devices presentation
FIOT_Unit_2 (1)softwaredefinedradio.pptx
FIot_Unit-3 fundAMENTALS OF IOT BASICS.pptx
fundamentals of iot cloud computing.pptx
Ad

Recently uploaded (20)

PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PPTX
Welding lecture in detail for understanding
PDF
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PDF
Structs to JSON How Go Powers REST APIs.pdf
PDF
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
PPTX
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PPTX
Lesson 3_Tessellation.pptx finite Mathematics
PDF
Well-logging-methods_new................
PPTX
Strings in CPP - Strings in C++ are sequences of characters used to store and...
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PDF
Arduino robotics embedded978-1-4302-3184-4.pdf
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PPTX
web development for engineering and engineering
PPTX
Internet of Things (IOT) - A guide to understanding
PPTX
Foundation to blockchain - A guide to Blockchain Tech
PPTX
Geodesy 1.pptx...............................................
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PPT
Mechanical Engineering MATERIALS Selection
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
Welding lecture in detail for understanding
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
Structs to JSON How Go Powers REST APIs.pdf
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
Lesson 3_Tessellation.pptx finite Mathematics
Well-logging-methods_new................
Strings in CPP - Strings in C++ are sequences of characters used to store and...
Model Code of Practice - Construction Work - 21102022 .pdf
Arduino robotics embedded978-1-4302-3184-4.pdf
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
web development for engineering and engineering
Internet of Things (IOT) - A guide to understanding
Foundation to blockchain - A guide to Blockchain Tech
Geodesy 1.pptx...............................................
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
Mechanical Engineering MATERIALS Selection

5-Tut3_Networking_with_Python.pptx good intro

  • 1. Tutorial 3 : Networking with Python| Learning Python on the Go.... 1
  • 2. IoT – Basic Idea 2
  • 3. Recall : Interfacing sensors to the computing unit Source: Book website: http://www.internet-of-things-book.com Raspberry Pi Breadboard Jumper wires Electrical components Sensors 3
  • 4. Vehicular Language : Python Installation, Guide, Docs.... www.python.org 4
  • 5. Recall : Programming the Raspberry Pi Learning Python on the Go....... The latest version of Raspbian includes the RPI.GPIO Python library pre-installed, so you can simply import that into your Python code. The RPI.GPIO is a library that allows your Python application to easily access the GPIO pins on your Raspberry Pi. The as keyword in Python allows you to refer to the RPI.GPIO library using the shorter name of GPIO. There are two ways to refer to the pins on the GPIO: either by physical pin numbers (starting from pin 1 to 40 on the Raspberry Pi 2/3), or Broadcom GPIO numbers (BCM) Module import GPIO pin setup Execute in loop Send a HIGH signal to pin 18 Wait for 1 time unit Send a LOW signal to pin 18 Wait for 1 time unit Python program which instructs the Rpi to blink a LED - turn the LED high and low alternately 5
  • 6. Interfacing Rpi to DHT11 Using the Adafruit DHT 11 library 1. git clone https://github.com/adafruit/Adafruit_Python_DHT.git 2. cd Adafruit_Python_DHT 3. sudo apt-get install build-essential python-dev 4. sudo python setup.py install Python program that instructs the Rpi to read data from the DHT11 module and print it 6
  • 7. The Four Layered IoT Architecture Source : ITU-T Focus of this tutorial 7
  • 9. Task : An application reads sequence of data inputs via some wireless protocol ex. Bluetooth 1. Start – Start receiving data 2. Acknowledgment – send acknowledgement about the last data packet 3. Data – sensing node sends data packet containing displacement and orientation information 4. Stop – stop processing in the sensing node Sensing Node (accelerometer) Commands : START, Data, STOP dx dy dz da Computation Displacement (x,y,z) 64 bit data over Bluetooth Acknowledgement Application 9
  • 10. Flow Chart showing Data Transfer begin Connect to the sensor node Send START command to sensor node Received n inputs? Send STOP to sensor node end Yes No receive data from sensor node Send Acknowledgement to sensor node 10
  • 11. Flow Chart showing Data Transfer Step 1 : Initialization begin Connect to the sensor node Send START command to sensor node Received n inputs? Send STOP to sensor node end Yes No receive data from sensor node device = 'COM3' baudrate = 115200 Btserial = open_device(devic e,baudrate) Send Acknowledgement to sensor node 11
  • 12. Flow Chart showing Data Transfer Step 2 : setting up the sensor node – send cmd begin Connect to the sensor node Send START command to sensor node Received n inputs? Send STOP to sensor node end Yes No receive data from sensor node device = 'COM3' baudrate = 115200 Btserial = open_device(device,baudrate) #write command to start interaction with the sensor node cmd = START write_device(btserial,cmd) Send Acknowledgement to sensor node cmd = header, payload,checksum Header is a single byte command ID Payloads could be multiple bytes command Last two bytes in any command are checksum. 12
  • 13. Flow Chart showing Data Transfer Step 3 : Check the number of packets received begin Connect to the sensor node Send START command to sensor node Received n inputs? Send STOP to sensor node end Yes No receive data from sensor node #read data and understand it pkt_len, num_rcvd = 64, 0 while (num_rcvd < 200): buffer = read_device(btserial, pkt_len) … #Send the ack to sensor node … #do processing of the payload … num_rcvd += 1 Send Acknowledgement to sensor node def read_device(device,length): buffer = [ ] device.flushInput() buffer = device.read(length) return buffer 13
  • 14. Flow Chart showing Data Transfer Step 4 : Receive data packets from sensor node begin Connect to the sensor node Send START command to sensor node Received n inputs? Send STOP to sensor node end Yes No receive data from sensor node #read data and understand it pkt_len = 64 buffer = read_device(btserial, pkt_len) valid,packet_info,payload = parse_pkt(buffer) if (valid == False): continue #do something with the info and payload Send Acknowledgement to sensor node 14
  • 15. Flow Chart showing Data Transfer Step 5 : Acknowledgement sent to sensor node begin Connect to the sensor node Send START command to sensor node Received n inputs? Send STOP to sensor node end Send Acknowledgement Yes No receive data from sensor node #read data and understand it pkt_len = 64 buffer = read_device(btserial, pkt_len) valid,packet_info,payload = parse_pkt(buffer) if (valid == False): continue #do something with the info and payload to sensor node Internet of Things Instructor : Dr. Bibhas Ghoshal #read data and understand it pkt_len = 64 buffer = read_device(btserial, pkt_len) valid,packet_info,payload = parse_pkt(buffer) if (valid == False): continue #Send the ack to the sensor node ack=create_ack(packet_info) write_device(btserial, ack) #do processing of the payload 15
  • 16. Flow Chart showing Data Transfer Step 6 : Send STOP command to the node begin Connect to the sensor node Send START command to sensor node Received n inputs? Send STOP to sensor node end Send Acknowledgement Yes No receive data from sensor node device = 'COM3' baudrate = 115200 Btserial = open_device(device,baudrate) #write command to start interaction with the sensor node cmd = START write_device(bt serial,cmd) #stop interacting with the sensor node cmd = STOP write_device(btserial,cmd) to sensor node 16
  • 17. Sockets Socket is a software object that acts as an end point of a bidirectional communication link between server and client programs on network Support in the operating system allows to implement clients and servers for both TCP and UDP communication. Python provides network service for server-client model. Python has additionally libraries which allow higher access to specific application level network protocols socket() connect() send() receive() close() send() socket() bind() listen() accept() receive() Connection Established request response C L I E N T S E R V E R Socket Programming (TCP) 17
  • 18. Sockets Socket is a software object that acts as an end point of a bidirectional communication link between server and client programs on network Sockets have two primary properties controlling the way they send data: the address family controls the OSI network layer protocol used and the socket type controls the transport layer protocol. Support in the operating system allows to implement clients and servers for both TCP and UDP communication. Python provides network service for server-client model. Python has additionally libraries which allow higher access to specific application level network protocols socket() bind() send to () rcvfrom () sendto() socket() bind() rcvfrom () request response C L I E N T S E R V E R Socket Programming (UDP) 18
  • 19. Ports Port is a number to identify the sender or receiver of message. Each host has 65,536 ports Ports 0-1023 are reserved. Protocol Port # Protocol Port # FTP 20 SMTP 25 SSH 22 HTTP 80 TELNET 23 HTTPS 443 Ports above 1024 are reserved for user processes. Socket must bound to port n server. 19
  • 20. Creating a Socket Getting Host Information gethostbyname(hostname) : Provide the IP address associated with a hostname gethostbyname_ex(hostname) >>> import socket >>> socket.gethostbyname('localhost') '127.0.0.1’ socket(family, type): Opens a socket, family is one of AF_UNIX or AF_INET type is one of SOCK_DGRAM or SOCK_STREAM # TCP socket S = socket.socket(socket.AF_INET,socket.SOCK 20
  • 21. Useful Functions on Socket accept() : accept a connection, returning new socket and client address bind(addr) : bind the socket to a local address close() : close the socket connect(addr) : connect the socket to a remote address listen(n) : start listening for incoming connections recv(buflen[, flags]) : receive data send(data[, flags]) : send data, may not send all of it 21
  • 22. TCP Server The socket module Provides access to low-level network programming functions. Example: A server that receives data and sends ack import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # TCP socket # Bind to local ip and port 8888 # Start listening, hold upto 5 connections s.bind(("",8888)) s.listen(5) while 1: client, addr = s.accept() # Wait for a connection print "Got a connection from ", addr data = client.recv(1024 # receive client's data upto 1024 byte print "Received data from client:", data client.send("Acknowledgement for received data") # Send ack back client.close() 22
  • 23. TCP Client The Client Program Connects to server, sends data and waits for ack import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Create TCP socket s.connect(("127.0.0.1",8888))# Connect to server s.send("Hello Server..") msg = s.recv(1024) s.close() # Send message to server # Receive up to 1024 bytes # Close connection print "Server's message:", msg 23
  • 24. Problems with the TCP Server Lots of repetitive coding Not really handling multiple (concurrent) clients Clients are queued Handled in sequential way Real world server would need concurrency Even more coding! 24
  • 25. Socket Server Python module to simplify creation of realistic servers Functionality to support basic network services such as HTTP, SMTP from help(SocketServer) Supports various server classes: TCPServer(address, handler) UDPServer(address, handler) ForkingTCPServer(address, handler) ForkingUDPServer(address, handler) ThreadingTCPServer(address, handler) ThreadingUDPServer(address, handler) Need to define request handler, Derive from BaseRequestHandler class Minimum requirement: define handle() method handle()called each time a connection request is received 25
  • 26. Useful Python Modules for Networking ftplib - for connecting to a ftp server smtplib - for sending emails urllib - To download contents of a URL httplib - communication over HTTP poplib/imaplib - email access protocols JavaScript Object Notation (JSON) – read and write data interchange format Tw o str uc tur es – i. col lec tio n of na m e, 26
  • 27. Example of a JSON and XML Format JSON Format {"menu": { "id": "file", "value": "File", "popup": { "menuitem": [ {"value": "New", "onclick": "CreateNewDo c()"}, {"value": "Open", "onclick": "OpenDoc()"} , {"value": "Close", "onclick": "CloseDoc()" } ] } }} The same text 27
  • 28. Encoding and Ecoding JSON in Python import json # A basic python dictionary py_object = {"c": 0, "b": 0, "a": 0} # Encoding json_string = json.dumps(py_object) print(json_string) print(type(json_string)) # Decoding JSON py_obj = json.loads(json_string) print() print(py_obj) print(type(py_obj)) Output: {"c": 0, "b": 0, "a": 0} <class 'str'> {'c': 0, 'b': 0, 'a': 0} <class 'dict'> 28
  • 29. GET and POST requests in Python 29
  • 30. GET requests in Python # importing the requests library import requests # api-endpoint URL = "http://maps.googleapis.com/maps/api/geocode/json" # location given here location = "iiita" # defining a params dict for the parameters to be sent to the API PARAMS = {'address':location} # sending get request and saving the response as response object r = requests.get(url = URL, params = PARAMS) # extracting data in json format data = r.json() # extracting latitude, longitude and formatted address # of the first matching location latitude = data['results'][0]['geometry']['location'] ['lat'] longitude = data['results'][0]['geometry']['location']['lng'] formatted_address = data['results'][0]['formatted_address'] # printing the output print("Latitude:%snLongitude:%snFormatted Address:%s %(latitude, longitude,formatted_address)) 30
  • 31. POST requests in Python # importing the requests library import requests # defining the api-endpoint API_ENDPOINT = "http://pastebin.com/api/api_post.php" # your API key here API_KEY = "XXXXXXXXXXXXXXXXX" # your source code here source_code = ''' print("Hello, world!") a = 1 b = 2 print(a + b) ''' # data to be sent to api data = {'api_dev_key':API_KEY, 'api_option':'paste', 'api_paste_code':source_code, 'api_paste_format':'python'} # sending post request and saving response as response object r = requests.post(url = API_ENDPOINT, data = data) # extracting response text pastebin_url = r.text print("The pastebin URL is:%s"%pastebin_url) 31