By B.A.Khivsara
PL-I Group A: Ass-6
Socket programming in Python
Outline
Socket Basics
Simple TCP Client Server Program
Chat TCP Client Server Program
File Transfer/Sharing Client Server Program
DataTransport
There are two basic types of communication
Streams (TCP): Computers establish a
connection with each other and read/write data in
a continuous stream of bytes---like a file. This is
the most common.
Datagrams (UDP): Computers send discrete
packets (or messages) to each other. Each
packet contains a collection of bytes, but each
packet is separate and self-contained.
UDP Characteristics
Also datagram-based
Connectionless, unreliable, can broadcast
Applications usually message-based
No transport-layer retries
Applications handle (or ignore) errors
Processes identified by port number
Services live at specific ports
Usually below 1024, requiring privilege
TCP Characteristics
Connection-oriented
Two endpoints of a virtual circuit
Reliable
Application needs no error checking
Stream-based
No predefined blocksize
Processes identified by port numbers
Services live at specific ports
Client/Server Concepts
Server opens a specific port
The one associated with its service
Then just waits for requests
Server is the passive opener
Clients get ephemeral ports
Guaranteed unique, 1024 or greater
Uses them to communicate with server
Client is the active opener
Sockets
•Programming abstraction for network code
•Socket: A communication endpoint
•Supported by socket library module
•Allows connections to be made and data to be
transmitted in either direction
socket socketnetwork
Socket API
Socket API
Network programming interface
Socket
APITCP UDP
IP
Application
Transport
Network
Socket Basics
•To create a socketimport socket
s = socket.socket(addr_family,Socket_type)
•Address families
socket.AF_INET Internet protocol (IPv4)
socket.AF_INET6 Internet protocol (IPv6)
•Socket typessocket.SOCK_STREAM Connection based stream (TCP)
socket.SOCK_DGRAM Datagrams (UDP)
Example:
from socket import *
s = socket(AF_INET,SOCK_STREAM)
Socket Basics
End point determined by two things:
Host address: IP address is Network Layer
Port number: is Transport Layer
Two end-points determine a connection: socket
pair
ex: 198.69.10.2, 5500
IP Address Port No
Ports Numbers (typical, since vary by OS):
0-1023 : reserved
1024-5000 : ephemeral
Above 5000 : for general use
(Total 65535 ports)
Well-known, reserved services
ftp 21/tcp
telnet 23/tcp
finger 79/tcp
snmp 161/udp
SocketTypes
•Almost all code will use one of following
from socket import *
s = socket(AF_INET,SOCK_STREAM)
s = socket(AF_INET,SOCK_DGRAM)
•TCP connection
s = socket(AF_INET, SOCK_STREAM)
•UDP connection
s = socket(AF_INET, SOCK_DGRAM)
Types of Sockets
Stream socket (TCP)
Connection-oriented Requires connection
establishment & termination
Reliable delivery In-order delivery Retransmission No duplicates
High variance in latency Cost of the reliable service
File-like interface (streaming)
E.g., HTTP, SSH, FTP, …
Datagram socket (UDP)
Connection-less
“Best-effort” delivery Possible out-of-order
delivery No retransmission Possible duplicates
Low variance in latency
Packet-like interface Requires packetizing
E.g., DNS, VoIP, VOD, AOD, …
Socket Functions socket() creates a new socket of a certain socket type, identified by an
integer number, and allocates system resources to it.
bind() is typically used on the server side, and associates a socket with a
socket address structure, i.e. a specified local port number and IP address.
listen() is used on the server side, and causes a bound TCP socket to
enter listening state.
connect() is used on the client side, and assigns a free local port number to
a socket. In case of a TCP socket, it causes an attempt to establish a new
TCP connection.
accept() is used on the server side. It accepts a received incoming attempt
to create a new TCP connection from the remote client, and creates a new
socket associated with the socket address pair of this connection.
send() and recv() are used for sending and receiving data to/from a remote
socket.
close() causes the system to release resources allocated to a socket.
gethostbyname() and gethostbyaddr() are used to resolve host names
and addresses. IPv4 only.
Outline
Socket Basics
Simple TCP Client Server Program
Chat TCP Client Server Program
File Transfer/Sharing Client Server Program
A simple TCP server
from socket import *
s = socket(AF_INET,SOCK_STREAM)
s.bind(("",5000))
s.listen(5)
while True:
c,a = s.accept()
print "Received connection from", a
c.send("Hello %s\n" % a[0])
c.close()
A Simple TCP Client
from socket import *
s = socket(AF_INET,SOCK_STREAM)
s.connect((“localhost",5000)) # Connect
s.send(“Hello”) # Send request
data = s.recv(10000) # Get response
s.close()
Outline
Socket Basics
Simple TCP Client Server Program
Chat TCP Client Server Program
File Transfer/Sharing Client Server Program
TCP Client for chatimport socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(("", 5000))
server_socket.listen(5)
while 1:
client_socket, address = server_socket.accept()
print "I got a connection from ", address
while 1:
data = raw_input ( "SEND( TYPE q or Q to Quit):" )
if (data == 'Q' or data == 'q'):
client_socket.send (data)
client_socket.close()
break;
else:
client_socket.send(data)
data = client_socket.recv(512)
if ( data == 'q' or data == 'Q'):
client_socket.close()
break;
else:
print "RECIEVED:" , data
TCP Client for chat
import socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(("localhost", 5000))
while 1:
data = client_socket.recv(512)
if ( data == 'q' or data == 'Q'):
client_socket.close()
break;
else:
print "RECIEVED:" , data
data = raw_input ( "SEND( TYPE q or Q to Quit):" )
if (data <> 'Q' and data <> 'q'):
client_socket.send(data)
else:
client_socket.send(data)
client_socket.close()
break;
Outline
Socket Basics
Simple TCP Client Server Program
Chat TCP Client Server Program
File Transfer/Sharing Client Server Program
TCP Server for File Sharingimport socket,os
s = socket.socket()
s.bind(("",12001))
s.listen(2)
while 1:
c,addr=s.accept()
path="/home/snjbcoe/PL-I Program"
dirlist=os.listdir(path)
flist=“ “
for fname in dirlist:
flist=flist+" "+fname
c.send(flist)
data=c.recv(1024)
f = open("/home/snjbcoe/PL-I Program/"+data, "rb")
a=f.read(5100)
c.send(a)
f.close()
c.close()
TCP Client for File Sharing
import socket
c=socket.socket()c.connect((“localhost",12001))
while 1:
print "File listing from server is\n",(c.recv(5000))
data=raw_input("enter file name to download\n :")
c.send(data)f=open(data,"wb")b=c.recv(5000)f.write(b)f.close()
print "File is downloaded successfuly“c.close()
References
http://www.dabeaz.com/python/PythonNetBinder.pdf
Top Related