1.动态导入模块
在当前目录下有lib和test目录,在test中要想使用lib中的aa的C类:
test中:
第一种方法:推荐
importlib.import_module('lib.aa')
obj = aa.c()
第二种方法:(python内部解释器用的)
lib = __import__("lib.aa")
obj = lib.aa.C()
2.断言:assert(预判,断定)
assert type("dsds") is str
print("yes")
如果断言错误,即"dsds"的类型不是str,则程序不能继续运行,会报错
若接下来的代码运行时非常重要,最好提前用断言
2.socket
Socket Families(地址簇)
socket.AF_UNIX unix本机进程间通信
socket.AF_INET IPV4
socket.AF_INET6 IPV6
Socket Types 类型
socket.SOCK_STREAM #for tcp
socket.SOCK_DGRAM #for udp
实际例子:
服务器端:
import socket
server = socket.socket()
server.bind(('localhost',6969))
server.listen(5)
print('The server is ready')
while True:
conn,addr = server.accept()
print('The client is connected !!!')
while True:
data = conn.recv(1024)
print('recv:',data.decode())
conn.send(data.upper())
server.close
客户端:
import socket
client = socket.socket()
client.connect(('localhost',6969))
while True:
msg = input('ibput>>').strip()
if len(msg) == 0:
continue
client.send(msg.encode('utf-8'))
data = client.recv(1024)
print('recv:',data.decode())
client.close()
实现回显数据:
服务器:
import socket,os
server = socket.socket()
server.bind(('localhost',6969))
server.listen(5)
print('The server is ready')
while True:
conn,addr = server.accept()
print('The client is connected !!!')
while True:
data = conn.recv(1024)
if not data:
break
# print('recv:',data.decode())
# conn.send(data.upper())
res = os.popen(data.decode()).read()
print('before send:',len(res))
if len(res) == 0:
res = 'cmd has no input'
conn.send(res.encode())
server.close
客户端:
import socket
client = socket.socket()
client.connect(('localhost',6969))
while True:
msg = input('ibput>>').strip()
if len(msg) == 0:
continue
client.send(msg.encode('utf-8'))
data = client.recv(1024)
print('recv:',data.decode())
client.close()
可以回显全部的数据
利用了循环知道返回全部的数据长度
服务器端:
import socket,os
server = socket.socket()
server.bind(('localhost',6969))
server.listen(5)
print('The server is ready')
while True:
conn,addr = server.accept()
print('The client is connected !!!')
while True:
data = conn.recv(1024)
if not data:
break
res = os.popen(data.decode()).read()
print('before send:',len(res))
if len(res) == 0:
res = 'cmd has no input'
conn.send(str(len(res.encode())).encode())
conn.send(res.encode())
server.close
客户端:
import socket
client = socket.socket()
client.connect(('localhost',6969))
while True:
msg = input('ibput>>').strip()
if len(msg) == 0:
continue
client.send(msg.encode('utf-8'))
data_size = client.recv(1024)
print("The size is :",data_size.decode())
received_size = 0
received_data = b''
while received_size < int(data_size.decode()):
data = client.recv(1024)
received_size += len(data)
received_data += data
print(received_size)
else:
print('cmd res receive done...',received_size)
print(data.decode())
client.close()
实现FTP的下载功能:
服务器:
import socket,os,hashlib
server = socket.socket()
server.bind(('localhost',6969))
server.listen(5)
print('The server is ready')
while True:
conn,addr = server.accept()
print('The client is connected !!!')
while True:
data = conn.recv(1024)
if not data:
print('The client is gone...')
break
cmd,filename = data.decode().split()
print(filename)
if os.path.isfile(filename):
f = open(filename,'rb')
m = hashlib.md5()
file_size = os.stat(filename).st_size
conn.send(str(file_size).encode())
conn.recv(1024) #wait for ack
for line in f:
m.update(line)
conn.send(line)
print('file md5',m.hexdigest())
f.close()
print('send done')
server.close
客户端:
import socket
client = socket.socket()
client.connect(('localhost',6969))
while True:
cmd = input('ibput>>').strip()
if len(cmd) == 0:
continue
if cmd.startwith('get'):
client.send(cmd.encode('utf-8'))
server_reponse = client.recv(1024)
print('server response:',server_reponse)
client.send(b'ready to recv file')
file_total_size = int(server_reponse.decode())
received_size = 0
filename = cmd.split()[1]
f = open(filename + '.new','wb')
while received_size < file_total_size:
data = client.recv(1024)
received_size += len(data)
f.write(data)
print(file_total_size,received_size)
else:
print('file recv done',file_total_size,received_size)
f.close()
client.close()
实现FTP的交互:
服务器:
import socketserver,json,os
class MyTCPHandler(socketserver.BaseRequestHandler):
def put(self,*args):
'''接收客户端文件'''
cmd_dic = args[0]
filename = cmd_dic['filename']
filesize = cmd_dic['size']
if os.path.isfile(filename):
f = open(filename+'.new','wb')
else:
f = open(filename,'wb')
self.request.send(b'200 ok')
received_size = 0
while received_size < filesize:
data = self.request.recv(1024)
f.write(data)
received_size += len(data)
else:
print('file [%s] has uploaded'%filename)
f.close()
def get(self,*args):
cmd_dic = args[0]
filename = cmd_dic['filename']
filesize = os.stat(filename).st_size
if os.path.isfile(filename):
self.request.send(str(filesize).encode())
client_request = self.request.recv(1024)
f = open(filename,'rb')
for line in f:
self.request.send(line)
else:
f.close()
else:
print('file [%s] is not exist...'%filename)
def handle(self):
while True:
try:
print('{} wrote:'.format(self.client_address[0]))
self.data = self.request.recv(1024).strip()
print(self.data)
cmd_dic = json.loads(self.data.decode())
action = cmd_dic['action']
if hasattr(self,action):
func = getattr(self,action)
func(cmd_dic)
except ConnectionResetError as e:
print('err',e)
break
if __name__ == '__main__':
HOST,PORT = 'localhost',9999
server = socketserver.ThreadingTCPServer((HOST,PORT),MyTCPHandler)
server.serve_forever()
客户端:
import socket,os,json
class FtpClient(object):
def __init__(self):
self.client = socket.socket()
def help(self):
msg = '''
ls
pwd
cd ../..
get filename
put filename
'''
print(msg)
def connect(self):
self.client.connect(('localhost',9999))
def interaction(self):
#self.authenticate()
while True:
cmd = input('>>').strip()
if len(cmd) == 0:continue
cmd_str = cmd.split()[0]
if hasattr(self,'cmd_%s'%cmd_str):
func = getattr(self,'cmd_%s'%cmd_str)
func(cmd)
else:
self.help()
def cmd_put(self,*args):
cmd_spilt = args[0].split()
if len(cmd_spilt) > 1:
filename = cmd_spilt[1]
if os.path.isfile(filename):
filesize = os.stat(filename).st_size
msg_dic = {
'action':'put',
'filename':filename,
'size':filesize,
'overridden':True
}
self.client.send(json.dumps(msg_dic).encode('utf-8'))
#防止粘包,等服务器确认
server_reponse = self.client.recv(1024)
f = open(filename,'rb')
for line in f:
self.client.send(line)
else:
print('file uupload success...')
f.close()
else:
print(filename,'is not exist')
def cmd_get(self,*args):
cmd_spilt = args[0].split()
if len(cmd_spilt) > 1:
filename = cmd_spilt[1]
msg_dic = {
'action': 'get',
'filename': filename
}
self.client.send(json.dumps(msg_dic).encode('utf-8'))
filesize = self.client.recv(1024)
self.client.send(b'200 ok')
if os.path.isfile(filename):
f = open(filename+'.new','wb')
else:
f = open(filename,'wb')
receive_size = 0
while int(filesize.decode()) > receive_size:
data = self.client.recv(1024)
f.write(data)
receive_size += len(data)
else:
print('file [%s] is downloaded...'%filename)
f.close()
ftp = FtpClient()
ftp.connect()
ftp.interaction()
使用方法:例如get filename 或者 put filename