python网络编程.pdf
《python网络编程.pdf》由会员分享,可在线阅读,更多相关《python网络编程.pdf(31页珍藏版)》请在淘文阁 - 分享文档赚钱的网站上搜索。
1、PythonNetwork Programmingby Sebastian V.TiponutTechnical University TimisoaraVersion 0.00,16.July 20012LIST OF FIGURESContents1Introduction42Basic socket usage52.1Creating a socket.52.2Connecting a socket and data transfer.62.3Binding a name to socket.62.4Listening and accepting connections.62.5UDP
2、sockets.72.6Closing the socket.72.7Using functions provided in socket module.82.7.1Functions based on resolver library.82.7.2Service-related functions.82.7.3Miscellaneous functions.83Basic network structures design93.1Designing a TCP server.93.2The TCP client.113.3Modeling datagram applications.114A
3、dvanced topics on servers134.1Building a pristine environment.134.2Handling multiple connections.134.2.1Threaded servers.144.2.2Using select.154.2.3Fork servers.164.3Dealing with classes.184.3.1Simple connection object.184.3.2Applying a design pattern.204.4Advanced aspects concerning clients.225HTTP
4、 protocol235.1CGI module.235.1.1Build a simple CGI script.235.1.2Using CGI module.245.1.3Configuring Apache on Linux for using with CGI scripts.256Common protocols266.1Designing Telnet applications.266.2File Transfer Protocol.286.3SMTP protocol.297TO DOs30List of Figures1TCP connection.92UDP connect
5、ion.10LIST OF FIGURES33Threaded server diagram.144Fork server diagram.175Designing a TCP connection with state pattern.2041INTRODUCTION1IntroductionNetwork programming is a buzzword now in the soft world.We see the market filled withan avalanche of network oriented applications like database servers
6、,games,Java servlets andapplets,CGI scripts,different clients for any imaginable protocol and the examples may con-tinue.Today,more then half of the applications that hit the market are network oriented.Data communication between two machines(on local net or Internet)is not any more a cu-riosity but
7、 is a day to day reality.“The network is the computer”says the Sun Microsystemsmotto and they are right.The computer is no more seen as a separate entity,dialogging onlywith its human operator but as part of a larger system-the network,bound via data linkswith other thousands of other machines.This
8、paper is presenting a possible way of designing network-oriented applications usingPython.Because the author is a Linux fan,the examples contained in this paper are relatedto Linux1and apologizes all the Windows or Mac OS users(fans?)for any inconvenienceon reading this text.With a little effort,the
9、 examples are portable to another non-UNIXoperation system.Presenting a quick structure of this paper,first four sections are dealingwith primitive design at socket level of network applications.The remaining sections aretreating specific protocols like http,ftp,telnet or smtp.The section dealing wi
10、th http willcontain a subsection about writing CGI scripts and using the cgi module.Going further on more concrete subjects,we are going to analyze the possibilities ofnetwork programming provided in Python.Raw network support is implemented in Pythonthrough the socket module,this module comprising
11、mostly of the system-calls,functions andconstants defined by the 4.3BSD Interprocess Communication facilities(see 1),implementedin object-oriented style.Python offers a simple interface(much simpler than the correspondingC implementation,though based on this one)to properly create and use a socket.P
12、rimarily,is defined the socket()function returning a socket object2.The socket has several methods,corresponding to their pairs from C sys/socket.h,like bind(),connect(),listen()oraccept().Programmers accustomed with socket usage under C language3will find very easyto translate their knowledge in th
13、e more-easy-to-use socket implementation under Python.Python eliminates the daunting task of filling structures like sockaddr in or hostent and easethe use of previously mentioned methods or functions parameter passing and functions callare easier to handle.Some network-oriented functions are provid
14、ed too:gethostbyname(),getprotobyname()or conversion functions ntohl(),htons(),useful when converting integersto and from network format.The module provides constants like SOMAXCONN,INADDR*,usedin gesockopt()or setsockopt()functions.For a complete list of above mentioned constantscheck your UNIX doc
15、umentation on socket implementation.Python provide beside socket,additional modules(in fact there is a whole bundle of them)supporting the most common network protocols at user level.For example we may find usefulmodules like httplib,ftplib,telnetlib,smtplib.There is implemented support for CGIscrip
16、ting through cgi module,a module for URL parsing,classes describing web serversand the examples may continue.This modules are specific implementations of well knownprotocols,the user being encouraged to use them and not trying to reinvent the wheel.Theauthor hopes that the user will enjoy the richne
17、ss of Pythons network programming facilitiesand use them in new and more exciting ways.Because all the examples below are written in Python,the reader is expected to be fluentwith this programming language.1And to other*NIX systems,POSIX compliant.2We call this further just socket.34.3BSD IPC implem
18、entation found on mostly UNIX flavors.2BASIC SOCKET USAGE52Basic socket usageThe socket is the basic structure for communication between processes.A socket is definedas“an endpoint of communication to which a name may be bound”1.The 4.3BSD imple-mentation define three communication domains for a soc
19、ket:the UNIX domain for on-systemcommunication between processes;the Internet domain for processes communicating overTCP(UDP)/IP protocol;the NS domain used by processes communicating over the old Xe-rox communication protocol.Python is using only4the first two communication domains:UNIX and Interne
20、t domains,the AF UNIX and AF INET address families respectively.UNIX domain addresses are repre-sented as strings,naming a local path:for example/tmp/sock.This can be a socket createdby a local process or,possibly,created by a foreign process.The Internet domain addressesare represented as a(host,po
21、rt)tuple,where host is a string representing a valid Internethostname,say matrix.ee.utt.ro or an IP address in dotted decimal notation andport isa valid port between 1 and 655355.Is useful to make a remark here:instead of a qualifiedhostname or a valid IP address,two special forms are provided:an em
22、pty string is usedinsteadINADDR ANY and the string instead of INADDR BROADCAST.Python offer all five type of sockets defined in 4.3BSD IPC implementation.Two seemto be generally used in the vastness majority of the new applications.A stream socket is aconnection-oriented socket,and has the underlayi
23、ng communication support the TCP proto-col,providing bidirectional,reliable,sequenced and unduplicated flow of data.A datagramsocket is a connectionless communication socket,supported through the UDP protocol.Itoffers a bidirectional data flow,without being reliable,sequenced or unduplicated.A proce
24、ssreceiving a sequence of datagrams may find duplicated messages or,possibly,in another orderin which the packets were sent.The raw,sequenced and reliably delivered message socketstypes are rarely used.Raw socket type is needed when one application may require access tothe most intimate resources pr
25、ovided by the socket implementation.Our document is focusingon stream and datagram sockets.2.1Creating a socketA socket is created through the socket(family,type,proto)call;family is one of theabove mentioned address families:AF UNIX and AF INET,type is represented through the fol-lowing constants:S
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- python 网络 编程
限制150内