文件下载器小案例

服务器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import socket


def send_file(client_socket, client_addr):
file_content = None
# 接收消息
recv_data = client_socket.recv(1024).decode("gbk")
print("%s 需要下载 %s" % (str(client_addr), recv_data))
# 打开文件
try:
f = open(recv_data, "rb")
file_content = f.read()
f.close()
except Exception as res:
print("没有需要下载的文件(%s)" % recv_data)
# 处理消息
if file_content:
client_socket.send(file_content)


def main():
# 创建socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定本地信息
server_socket.bind(("", 8080))
# 设主动为被动
server_socket.listen(128)
while True:
# 监听
client_socket, client_addr = server_socket.accept()
# 调用函数
send_file(client_socket, client_addr)
client_socket.close()
server_socket.close()


if __name__ == "__main__":
main()

客户端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import socket


def main():
# 创建socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 链接服务器
client_socket.connect(("10.198.207.67", 8080))
# 获取下载的文件名称
download_file_name = input("请输入下载的文件名:")
# 将文件名发送给服务器
client_socket.send(download_file_name.encode("gbk"))
# 接收文件中的数据
recv_data = client_socket.recv(1024)
# 保存接收到的数据到同一个文件中
if recv_data:
with open("[下载]" + download_file_name, "wb") as f:
f.write(recv_data)
# 关闭socket
client_socket.close()


if __name__ == "__main__":
main()

评论



2019-2021 覃浩的博客 鄂ICP备19020398号-4 正在载入...

PoweredHexo
HostedGitHub & Coding
DNSAliyun & DNSPod
CDNjsDelivr
PictureBedjsDelivr
ThemeVolantis