Python Network programming common code

Source: Internet
Author: User
Server-side code:

#-*-coding:cp936-*-import Socket sock = Socket.socket (socket.af_inet, socket. SOCK_STREAM) #初始化socket Sock.bind (("127.0.0.1", 8001) #绑定本机地址, 8001 Port Sock.listen (5) #等待客户连接 while True:  print " Waiting client Connection ... "  connection,address = sock.accept () #接收客户连接请求  print" A client has connected ... " While  True:    try:       connection.settimeout (5) #设置超时时间      buf = connection.recv (1024x768) #接收数据      if buf = = "1" :         connection.send ("You had send me 1!welcome to server!")      Elif buf== "2":        connection.send ("You have send me 2! I have recv! ")      Elif buf== "3":        connection.send ("Close the connection!")        Break      Else:         connection.send ("Unknow command!")     Except Socket.timeout:       print "Time Out"   connection.close ()  print "A client exit ..."

Client Side code:

Import Socket sock = Socket.socket (socket.af_inet, socket. Sock_stream) Sock.connect (("127.0.0.1", 8001)) Import time Time.sleep (2) while True:  data=raw_input ("Input command :");  Sock.send (data)  print sock.recv (1024x768)  if data== "3":    Breaksock.close ()

1. Open the server-side and client-side code by opening two idle first.
2.f5 running server-side code, waiting client connection will appear ...
3.f5 Run the client code, the input command will appear:;
4. Then the server and the client are connected, can communicate properly,

5. The error occurs when running server-side code again, this can be done by the Task Manager, the Pythonw.exe process will be completed, re-open, compile it!

Client:

Import Sockets=socket.socket () host = Socket.gethostname () port = 1234s.connect ((host, port)) print S.RECV (1024)

Service side:

Import sockets = Socket.socket () host = Socket.gethostname () port = 1234s.bind ((host, Port)) S.listen (5) while true:c, addr = S.accept () print ' Got connection from ', addr c.send (' Thank-for-connecting ') C.close ()

HTTP programming

From urllib Import urlopenwebpage = Urlopen (' http://www.python.org ')

Plus regular expressions.

Import Retext = Webpage.read () m = Re.search (' <a href= ' ([^ ']+ ') ' .*?>about</a> ', text, re. IGNORECASE) M.group (1)

Urllib
Urllib2

An example of a small server based on Socketserver:

From Socketserver import TCPServer, streamrequesthandler>>> class Handler (streamrequesthandler):d EF handle ( Self): addr = Self.request.getpeername () print ' Got connection from ', Addrself.wfile.write (' Thank-for-connecting ') >>> Server = TCPServer ((' ', 1234), Handler) >>> server.serve_forever ()

Fork and thread processing using Socketserver
Fork Server:

From Socketserver import Tcpserver,forkingminin, Streamrequesthandlerclass Server (Forkingminin, tcpserver):p Assclass Handler (Streamrequesthandler): def handle (self):  addr = Self.request.getpeername ()  print ' Got connection From ', addr  self.wfile.write (' Thank to connection ') Server = Server ((' ', 1234), Handler) Server.serve_forever ()

Thread Server:

From Socketserver import TCPServer, ThreadingMixIn, Streamrequesthandlerclass Server (ThreadingMixIn, TCPServer): Passclass Handler (streamrequesthandler): def handle (self):  addr = Self.request.getpeername ()  print ' Got Connection from ', addr  self.wfile.write (' Thank to connecting ') Server = Server ((' ', 1234), Handler) Server.serve _forever ()

asynchronous I/O with select and pool
Select service:

Import socket, selects = Socket.socket () host = Socket.gethostname () prot = 1234s.bind ((host,port)) S.listen (5) inputs = [s] While true:rs,ws,es = Select.select (inputs,[],[]) for R in RS:  if R is s:  c, addr = S.accept ()  print ' Got con Nection from ', addr  inputs.append (c) Else:  try:   data = R.RECV (1024x768)   disconnected = Not data  Except Socket.error:   disconnected = True     if disconnected:   print r.getpeername (), ' Disconnected '   Inputs.remove (R)  else:   print data

Pool server:

Import socket, selects = Socket.socket () host = Socket.gethostname () port = 1234s.bind ((host, port)) Fdmap = {S.fileno (): s}  S.listen (5) p = select.poll () p.register (s) while true:events = P.poll () for FD, event in events:  if FD in Fdmap:   C, addr = s.accept ()   print ' Got connection from ', addr   p.register (c)   Fdmap[c.fileno ()]=c  elif Event & Select. Pollin:   data = FDMAP[FD].RECV (1024x768)   if not data:    print fdmap[fd].getpeername (), ' Disconnected '    P.unregister (FD)    del fdmap[fd]  else:   print data


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.