这个项目的本质是在tcp服务器上的一次演进,将客户端与服务器之间的数据流记录到文件当中。代码中初步加入了异常捕获,因为没有使用多进程等技术,看起来还是挺简陋的。
客户端的代码书写
import socket
def main():
client_sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
dest_ip = input("请输入下载服务器的ip:")
dest_port = int(input("请输入服务器的端口:"))
client_sock.connect((dest_ip,dest_port))
down_file = input("请输入要下载的文件名")
client_sock.send(down_file.encode("utf-8"))
recv_data = client_sock.recv(1024)
#对于with 写法有效的保证了打开文件后的异常,但对于打开文件时出现异常无能为力
if recv_data:
with open("[新]"+down_file,"wb") as f:
f.write(recv_data)
client_sock.close()
if __name__ == "__main__":
main()
服务器端的代码书写
import socket
def send_file_2_client(new_client_socket,client_addr):
file_name = new_client_socket.recv(1024).decode("gbk")
print("客户端(%s)需要下载的文件是:%s" % (str(client_addr), file_name))
file_content = None
#这个地方避免打卡文件异常,因为经常会有文件异常
try:
f = open(file_name,"rb")
file_content = f.read()
f.close()
except Exception as ret:
print("没有要下载的文件(%s)" % file_name)
#在客户端和这里都加入了文件是否存在的判断
if file_content:
new_client_socket.send(file_content)
def main():
tcp_serve_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
tcp_serve_socket.bind(("",7788))
tcp_serve_socket.listen(128)
while True:
new_client_socket,client_addr = tcp_serve_socket.accept()
# file_name = new_client_socket.recv(1024).decode("gbk")
# print("客户端(%s)需要下载的文件是:%s" % (str(client_addr),file_name))
# new_client_socket.send(b"tangsai----ok-----")
send_file_2_client(new_client_socket, client_addr)
new_client_socket.close()
tcp_serve_socket.close()
if __name__ == "__main__":
main()
这个项目到后面还很大的修改空间