python学习之网络编程
2012-06-02 11:32
405 查看
socket模块
小型服务器
小型客户机
urllib,urllib2模块
urlopen 返回的类文件对象支持close,read,readline,readlines方法,也支持迭代
urlretrieve 获取远程文件并保存
SocketServer
类似于上面的服务器端代码
使用SocketServer进行分叉和线程处理
分叉:并行时间,两份内存
线程:共享内存
带有select和poll的异步I/O
aa
小型服务器
import socket s = socket.socket() host = socket.gethostname() port = 5000 s.bind((host, port)) s.listen(5) while True: c, addr = s.accept() ##(clinet, address) print 'get collection from ', addr c.send('Thank you for connecting') c.close()
小型客户机
import socket s = socket.socket() host = socket.gethostname() port = 5000 s.connect((host, port)) print s.recv(1024)
urllib,urllib2模块
urlopen 返回的类文件对象支持close,read,readline,readlines方法,也支持迭代
from urllib import urlopen webpage = urlopen('http://douban.com') while True: line = webpage.readline() if not line: break webpage.close()
urlretrieve 获取远程文件并保存
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
相关文章推荐
- python学习第十四章——网络编程
- python 网络编程学习: 1 初识 SOCKET
- Python基础学习(5)网络编程socket、文件上传、粘包问题、socketserver、IO多路复用、线程与进程、进程池、线程池、上下文管理、协程
- Python学习笔记:网络编程(socket)
- python学习笔记(六)网络编程
- Python学习笔记(七) -- Python Socket 网络编程
- Python学习笔记16:网络编程
- 深度学习与神经网络-吴恩达(Part1Week4)-深度神经网络编程实现(python)-基础篇
- <<Python基础教程>>学习笔记 | 第14章 | 网络编程
- 迟迟开始学习的网络编程,C语言客户端服务端,python客户端服务端和mini木马
- Python学习笔记(4)-- 网络编程(1)-- socket
- 深度学习与神经网络-吴恩达(Part1Week3)-单隐层神经网络编程实现(python)
- python学习八:网络编程初探
- Python 网络编程相关知识学习
- 23. Python脚本学习笔记二十三网络编程
- python学习——socket网络编程
- python 网络编程学习 - 1
- Python学习之网络编程Socket
- python学习(20) 网络编程
- python学习之网络编程