您的位置:首页 > 理论基础 > 计算机网络

python学习之网络编程

2012-06-02 11:32 405 查看
socket模块

小型服务器

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: