Network programming of Python notes

Source: Internet
Author: User

1, to learn this part, you should first understand the OSI 7 layer model, TCP/IP four layer, socket sockets and other network-related knowledge points. Python network library, URLLIB,URLLIB2, the latter features a bit more powerful.
Import Urllib2import urllibresponse = Urllib2.urlopen (' http://www.baidu.com ') #获取百度首页的代码, open the remote file Urllib.urlretrieve (' Http://www.baidu.com ', ' baidu_index.html ')     #下载文件并保存到本地html = Response.read () print HTML
There are other modules, such as Smtplib,email,cgi,httplib,ftplib,cookie, are now available for inspection.
2,socket ModuleServer-side demo
Import sockets = Socket.socket () #host = Socket.gethostname () port = 1234s.bind ((host,port)) S.listen (5) while True:     C , addr = s.accept ()     print ' Client link from: ', addr     c.send (' Hello, client. This is server ')     c.close ()

the Socketserver module simplifies server-side programming.
From Socketserver import Tcpserver,streamrequesthandlerclass Handler (streamrequesthandler):d EF handle (self):     # Processing is placed in the handle method addr = Self.request.getpeername () print ' Get link from: ', Addrself.wfile.write (' Welcome, link succeed ') Server = TCPServer (("', 1234), Handler) Server.serve_forever () #begin to listen and handle link
#运行结果bowen: ~ bowen$ vimsocketserver_server.pybowen:~ bowen$ python socketserver_server.pyget link from: (' 192.168.42.184 ', 49533)

Client Demo
Import sockets = Socket.socket () host = Socket.gethostname () port = 1234s.connect ((host,port))     #连接服务器print S.recv ( 1024x768) S.close ()

Server and Client communication demo
bowen: Python bowen$ cat Server.pyimport socketsock = Socket.socket (socket.af_inet, socket. SOCK_STREAM) #create socketsock.bind ((' localhost ', 8001)) #bind IP and Portsock.listen (5) #start listeningwhile True: CONN,ADDR = sock.accept () print ' link from: ', Addrtry:conn.settimeout (5) Buff = CONN.RECV (1024x768) if buff = = ' 1 ': conn.send (' Welcome to Server ") #send msg to Clientelse:conn.send (' plead go out ') except Socket.timeout:print ' Time out exception ' Conn. Close () #close Linkbowen:python bowen$ cat client.pyimport socketimport timesock = Socket.socket () sock.connect (' localhost ', 8001)) Time.sleep (2) sock.send (' 1 ') print sock.recv (1024x768) #recv msg from Serversock.close () 
#运行结果bowen: ~ bowen$ vimsocketserver_server.pybowen:~ bowen$ python socketserver_server.pyget link from: (' 192.168.42.184 ', 49533)

3, asynchronous communication1, fork mode (forkingmixin); The server class provides multi-connection processing, and data transfer services.
From Socketserver import Tcpserver,forkingmixin,streamrequesthandlerclass Server (Forkingmixin, tcpserver):p Assclass Handler (streamrequesthandler):d EF handle (self): addr = Self.request.getpeername () print ' Get link from: ', Addrself.wfile.write (' Many links by fork ') if __name__ = = ' __main__ ': Server = Server (' localhost ', 1234), Handler) Server.serve_forever ()

2, Threading mode (ThreadingMixIn), similar to fork processing, except that the server inherits the ThreadingMixIn
From Socketserver import Tcpserver,threadingmixin,streamrequesthandlerclass Server (ThreadingMixIn, TCPServer): Passclass Handler (streamrequesthandler):d EF handle (self): addr = Self.request.getpeername () print ' Get link from: ', Addrself.wfile.write (' Many links in Thread ') if __name__ = = ' __main__ ': Server = Server ((' localhost ', 1234), Handler) Server.serve_forever ()

3, asynchronous I/O mode, the Select () method is used to monitor the specified file descriptor and respond when the descriptor changes. The poll () method can also be implemented.
Import socket, selects = Socket.socket () s.bind ((' localhost ', 1234)) S.listen (5) inputs = [s] #store socket reqwhile True:rs , Ws,es = Select.select (inputs,[],[]) #use Select () for R in Rs:if r is s:conn,addr = s.accept () print ' Get link form: ', Addrin Puts.append (conn) #put socket conn into  inputselse:try:    data = R.RECV (1024x768)    disconnected = not dataexcept Socket.error:    disconnected = Trueif disconnected:    print r.getpeername (), ' Disconnected '    inputs.remove (r ) Else:<span style= "White-space:pre" ></span>    print Data


Network programming of Python notes

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.