python学习之网络编程
socket模块
小型服务器
1 import socket 2 3 s = socket.socket() 4 5 host = socket.gethostname() 6 port = 5000 7 s.bind((host, port)) 8 s.listen(5) 9 10 while True: 11 c, addr = s.accept() ##(clinet, address) 12 print 'get collection from ', addr 13 c.send('Thank you for connecting') 14 c.close()
小型客户机
1 import socket 2 3 s = socket.socket() 4 5 host = socket.gethostname() 6 port = 5000 7 8 s.connect((host, port)) 9 print s.recv(1024)
urllib,urllib2模块
urlopen 返回的类文件对象支持close,read,readline,readlines方法,也支持迭代
1 from urllib import urlopen 2 webpage = urlopen('http://douban.com') 3 while True: 4 line = webpage.readline() 5 if not line: 6 break 7 webpage.close()
urlretrieve 获取远程文件并保存
1 urlretrieve('http://douban.com', '/tmp/douban.html')
SocketServer
类似于上面的服务器端代码
import SocketServer class MyTCPHandler(SocketServer.BaseRequestHandler): """ The RequestHandler class for our server. It is instantiated once per connection to the server, and must override the handle() method to implement communication to the client. """ def handle(self): # self.request is the TCP socket connected to the client self.data = self.request.recv(1024).strip() print "%s wrote:" % self.client_address[0] print self.data # just send back the same data, but upper-cased self.request.send(self.data.upper()) if __name__ == "__main__": HOST, PORT = "localhost", 9999 # Create the server, binding to localhost on port 9999 server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler) # Activate the server; this will keep running until you # interrupt the program with Ctrl-C server.serve_forever()
使用SocketServer进行分叉和线程处理
分叉:并行时间,两份内存
线程:共享内存
带有select和poll的异步I/O
aa
浙公网安备 33010602011771号