案例:文件下载器
服务器 参考代码如下:
from socket import *
import sys
def get_file_content(file_name):
"""获取文件的内容"""
try:
with open(file_name, "rb") as f:
content = f.read()
return content
except:
print("没有下载的文件:%s" % file_name)
def main():
if len(sys.argv) != 2:
print("请按照如下方式运行:python3 xxx.py 7890")
return
else:
port = int(sys.argv[1])
tcp_server_socket = socket(AF_INET, SOCK_STREAM)
address = ('', port)
tcp_server_socket.bind(address)
tcp_server_socket.listen(128)
while True:
client_socket, clientAddr = tcp_server_socket.accept()
recv_data = client_socket.recv(1024)
file_name = recv_data.decode("utf-8")
print("对方请求下载的文件名为:%s" % file_name)
file_content = get_file_content(file_name)
if file_content:
client_socket.send(file_content)
client_socket.close()
tcp_server_socket.close()
if __name__ == "__main__":
main()
客户端 参考代码如下:
from socket import *
def main():
tcp_client_socket = socket(AF_INET, SOCK_STREAM)
server_ip = input("请输入服务器ip:")
server_port = int(input("请输入服务器port:"))
tcp_client_socket.connect((server_ip, server_port))
file_name = input("请输入要下载的文件名:")
tcp_client_socket.send(file_name.encode("utf-8"))
recv_data = tcp_client_socket.recv(1024)
if recv_data:
with open("[接收]"+file_name, "wb") as f:
f.write(recv_data)
tcp_client_socket.close()
if __name__ == "__main__":
main()