socket

client_test.py

#client
import socket
s=socket.socket()
host=socket.gethostname()
port=1234
s.connect((host,port))  #使用的地址与bind方法中地址相同
print(s.recv(1024).decode('utf-8'))
s.send(b'thanks again from client\r\n')
s.close()

Server_test.py

#server
#阻塞,同步网络编程
import socket
s=socket.socket() #地址族,流或数据报套接字,使用的协议
host=socket.gethostname()
port=1236   #低于1024的端口号用于标准服务
s.bind((host,port))
s.listen(5) #参数服务器未处理的连接的长度(即允许排队等待的连接数目)
while True:
    c,addr=s.accept()
    print('got connection from',addr)
    #python 3.2 socket.send传送数据必须是byte
    #c.send(bytes('thanks for connection','UTF-8'))
    c.send(b'thanks for connection')
    print(c.recv(1024).decode('utf-8')) #收到b'Hello' 删掉前面b
    c.close()
s.close()

SocketServer.py

#SocketServer
'''
SocketServer是标准库中很多服务器框架的基础,这些框架包括BaseHTTPServer,SimpleHTTPServer,
CGIHTTPServer,SimpleXMLRPCServer,DocXMLRPCServer,
所有这些服务器框架都为基础服务器增加了特定的功能
SockerServer包含4个基本的类,针对TCP套接字流的TCPServer,UDP数据报套接字的UDPServer,
以及针对性不强的UnixStreamServer和UnixDatagramServer
'''
from socketserver import TCPServer,StreamRequestHandler
class Handler(StreamRequestHandler):
    def handle(self):
        addr=self.request.getpeername()
        print('from',addr)
        self.wfile.write(b'thanks')
        print(self.rfile.read(1024).decode())
server=TCPServer(('',1234),Handler)
server.serve_forever()

'''
为了写一个使用SocketServer框架的服务器,大部分代码会在一个请求处理程序中(request handler)。
每当服务器收到一个请求(来自客户端的连接)时,就会实例化一个请求处理程序,
并且他的各种处理程序类(handler class),这样可以把他们子类化,使得服务器调用自定义的处理程序集。
基本的BaseRequestHandle类把所有的操作都放到了处理器的一个叫做handle的方法中,
这个方法会被服务器调用。
然后这个方法就会访问属性self.request中的客户端套接字
如果使用的是流(如果使用的是TCPServer,这就是可能的),那么可以使用StreamRequestHandler类,
创建了其他两个新属性,self.rfile(用于读取)和self.wfile(用于写入)
然后就能使用这些类文件对象和客户机进行通信
'''

urllib_test.py

#通过网络访问文件
#from urllib import urlopen
from urllib.request import urlopen #python3的库位置跟python2的有点不同
from urllib.request import urlretrieve
import re
webpage=urlopen('http://www.baidu.com')
'http://www.python.org'
#urlopen返回的类文件对象支持close,read,readline,readlines方法
#text=webpage.read().decode('utf-8')
text=webpage.read().decode()
'''
m=re.search('<a href="([^"]+)" .*?>about</a>',text,re.IGNORECASE)
print(m.group(1))
'''
#访问本地文件,用以file开头的URL访问本地文件,试验urllib是否在线
webpage=urlopen(r'file:D:\program files\Python34\PyWorks\ABBREV.txt')
print(webpage.read())

#希望urllib为你下载文件并在本地文件中存储一个文件的副本,可以使用urlretrieve
#urlretrieve返回一个元组(filename,headers)
#filename是本地文件的名字,headers包含一些远程文件的信息
filename,headers=urlretrieve('http://www.baidu.com','c:\\a.html')
print('filename:\n',filename,'\n')
print('headers:\n',headers)

filename,headers=urlretrieve(r'file:D:\program files\Python34\PyWorks\ABBREV.txt',
                             'c:\\a.txt')
print('filename:\n',filename,'\n')
print('headers:\n',headers)

 

posted @ 2016-06-26 15:04  *飞飞*  阅读(447)  评论(0编辑  收藏  举报