上一篇:TCP协议 | 手把手教你入门Python之九十七
下一篇:多线程实现多任务 | 手把手教你入门Python之九十九
本文来自于千锋教育在阿里云开发者社区学习中心上线课程《Python入门2020最新大课》,主讲人姜伟。
文件下载案例
TCP服务器端:
import socket, os
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('192.168.31.199', 9090))
server_socket.listen(128)
# 接收客户端的请求
client_socket, client_addr = server_socket.accept()
file_name = client_socket.recv(1024).decode('utf8')
# print('接收到了来自{}地址{}端口的数据,内容是:{}'.format(client_addr[0], client_addr[1], data))
if os.path.isfile(file_name):
# print('读取文件,返回给客户端')
with open(file_name, 'rb') as file:
content = file.read()
client_socket.send(content)
else:
print('文件不存在')
TCP客户端:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('192.168.31.199', 9090))
# s.send('hello'.encode('utf8'))
file_name = input('清输入您要下载的文件名:')
s.send(file_name.encode('utf8'))
with open(file_name, 'wb') as file:
while True:
content = s.recv(1024)
if not content:
break
file.write(content)
s.close()