socket.socket() returns socket object: _socketobject most of socket api are methods on socket...
TRANSCRIPT
socket.socket() returns socket object: _socketobject Most of socket API are methods on socket objects or functions Value result arguments (e.g., socket address) become return val-ues Socket address is a tuple: (host, port) sendall == writen() in UNP
Echo Client and Iterative Server
SocketServer (socketserver in Python 3)A Framework for Network ServerIterative Multi-threads Processes
BaseServer ThreadingMixIn ForkingMixIn
TCPServer ThreadingTCPServer ForkingTCPServer
UnixStreamServer ThreadingUnixStreamServer ForkingUnixStreamServer
UDPServer ThreadingUDPServer ForkingUDPServer
UnixDatagram-Server
ThreadingUnixDatagram-Server
ForkingUnixDatagram-Server
Class Inheritance
BaseRequestHandler
StreamRequestHandler Support file-like methods- self.rfile: buffered- self.wfile: unbuffered
DatagramRe-questHandler
Support StringIO- self.rfile and self.wfil
Server Classes Inheritance
Handler Classes Inheritance
server = ThreadingTCPServer((‘’, port)), StreamRequestHandler)server.serve_forever()
handle() method 만 작성하면 충분 !!
Running Server
thread module (_thread in Python 3)◦ Low-level thread use threading module
threading module: object-oriented way on the thread module◦ Define target function ◦ or write subclass of Thread overriding run() method
Threads in Python
Thread Functions and Subclassesimport timefrom threading import Thread
def sleeper(i): print "thread %d sleeps for 5 seconds" % i time.sleep(5) print "thread %d woke up" % i
for i in range(10): t = Thread(target=sleeper, args=(i,)) t.start()
import threading, zipfile
class AsyncZip(threading.Thread): def __init__(self, infile, outfile): threading.Thread.__init__(self) self.infile = infile self.outfile = outfile def run(self): f = zipfile.ZipFile(self.outfile, 'w', zipfile.ZIP_DEFLATED) f.write(self.infile) f.close() print 'Finished background zip of: ', self-.infile
background = AsyncZip('mydata.txt', 'myarchive.zip')background.start()print 'The main program continues to run in fore-ground.'
background.join() # Wait for the background task to finishprint 'Main program waited until background was done.'
Override run() method
Lock, Rlock, Condition, Semaphore, BoundedSemapore objectsimport threading
some_lock = threading.Lock()
with some_lock: print "some_rlock is locked while this executes"
Queue: A synchronized queue classdef worker(): while True: item = q.get() do_work(item) q.task_done()
q = Queue()for i in range(num_worker_threads): t = Thread(target=worker) t.daemon = True t.start()
for item in source(): q.put(item)
q.join() # block until all tasks are done
Internet Access>>> import urllib2>>> for line in urllib2.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'):... if 'EST' in line or 'EDT' in line: # look for Eastern Time... print line
<BR>Nov. 25, 09:43:32 PM EST
>>> import smtplib>>> server = smtplib.SMTP('localhost')>>> server.sendmail('[email protected]', '[email protected]',... """To: [email protected]... From: [email protected]...... Beware the Ides of March.... """)>>> server.quit()
struct — Interpret strings as packed binary dataimport structsource_ip = '192.168.1.101'dest_ip = '192.168.1.1' # or socket.gethostbyname('www.google.com') # ip header fieldsip_ihl = 5ip_ver = 4ip_tos = 0ip_tot_len = 0 # kernel will fill the correct total lengthip_id = 54321 #Id of this packetip_frag_off = 0ip_ttl = 255ip_proto = socket.IPPROTO_TCPip_check = 0 # kernel will fill the correct checksumip_saddr = socket.inet_aton ( source_ip ) #Spoof the source ip address if you want toip_daddr = socket.inet_aton ( dest_ip ) ip_ihl_ver = (version << 4) + ihl # the ! in the pack format string means network orderip_header = struct.pack('!BBHHHBBH4s4s' , ip_ihl_ver, ip_tos, ip_tot_len, ip_id, ip_frag_off, ip_ttl, ip_proto, ip_check, ip_saddr, ip_daddr)