Python Network programming common code Snippets _python

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 have Connected ... "While
  True:
    try: 
      connection.settimeout (5) #设置超时时间
      buf = CONNECTION.RECV (1024) # Receive Data
      if buf = = "1": 
        connection.send ("You have 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 (1024)
  if data== "3":
    break
Sock.close ()

1. First open two idle, the server-side and client-side code are opened separately.
2.f5 running server-side code, there will be waiting client connection ...
3.f5 running client code, the input command appears:;
4. At this time the server and the client connected, you can normal communication, as shown:

5. Run the server-side code again, there will be errors, then you can through the Task Manager, the Pythonw.exe process will be completed, reopened, compile on it!

Client:

Import Socket
S=socket.socket ()
host = Socket.gethostname ()
port = 1234
S.connect (host, Port)
Print S.RECV (1024)

Service side:

Import socket
s = socket.socket ()
host = Socket.gethostname ()
port = 1234
S.bind (host, Port
 
) S.listen (5)
while True:
 c, addr = S.accept ()
 print "Got connection from", Addr
 c.send (' Thank for Conn Ecting ')
 c.close ()

HTTP programming

From urllib import urlopen
webpage = urlopen (' http://www.python.org ')

Plus regular Expressions

import re
text = 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):
	def handle (self):
		addr = Self.request.getpeername ()
		print ' Got connection from ', addr self.wfile.write
		(' Thank for connecting ')
 
>>> server = TCPServer ((', 1234), Handler)
>>> server.serve_ Forever ()

Fork and thread handling using Socketserver
Fork Server:

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

Thread Server:

From Socketserver import TCPServer, ThreadingMixIn, Streamrequesthandler
class Server (ThreadingMixIn, TCPServer): Pass
class Handler (Streamrequesthandler):
 def handle (self):
  addr = Self.request.getpeername ()
  print ' Got connection from ', addr
  self.wfile.write (' Thank for connecting ')
Server = Server ((', 1234), Handler)
Server.serve_forever ()

asynchronous I/O with select and pool
Select service:

Import socket, select
s = Socket.socket ()
host = Socket.gethostname ()
prot = 1234
s.bind ((host,port)) C5/>s.listen (5)
inputs = [s] while
True:
 rs,ws,es = Select.select (inputs,[],[]) for
 R in RS:
  if R are s:
  c, addr = S.accept ()
  print ' Got connection from ', addr
  inputs.append (c)
 else:
  try:
   data = R.RECV (1024)
   disconnected = not data
  except Socket.error:
   disconnected = True
   
  If Disconnected:
   print r.getpeername (), ' Disconnected '
   inputs.remove (R)
  else:
   print data

Pool server:

Import socket, select
s = Socket.socket ()
host = Socket.gethostname ()
port = 1234
S.bind (host, Port) C5/>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 ', ad Dr
   P.register (c)
   Fdmap[c.fileno ()]=c
  elif event & Select. Pollin:
   data = FDMAP[FD].RECV (1024)
   if not data:
    print fdmap[fd].getpeername (), ' Disconnected '
    P.unregister (FD)
    del fdmap[fd]
  else:
   print data

Twisted Network Framework

Http://www.jb51.net/article/64199.htm

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.