在上一篇文章中完成了TCP通信的基本操作,本文中完成TCP的文件下载操作。
客户端代码:
import socket
def main():
#1.创建
tcp_client = socket.socket(family=socket.AF_INET,type=socket.SOCK_STREAM)
#2.ip port
tcp_client.connect(('192.168.152.1',7892))
fileName = input('请输入要下载的文件名:')
#3.发消息 说明下载的文件名字
tcp_client.send(fileName.encode())
#4.收到消息
recv_content = tcp_client.recv(1024*1024)
print(recv_content)
#5.写入
with open('副本'+fileName,'ab') as f:
f.write(recv_content)
tcp_client.close()
if __name__ == '__main__':
main()
服务器端代码:
import socket
def main():
#1.创
tcp_server = socket.socket(family=socket.AF_INET,type=socket.SOCK_STREAM)
#2.绑定
tcp_server.bind(('',7892))
#3.设置为可以连接的
tcp_server.listen(128)
#4.阻塞
new_socket,client_addr = tcp_server.accept()
#5.将文件内容发出去……下载都是这么搞的吗
tcp_send(new_socket)
tcp_server.close()
#具体的读取文件和发送数据的操作过程
def tcp_send(new_socket):
fileName = new_socket.recv(1024*1024).decode('gbk')
print(fileName)
try:
with open(fileName,'rb') as f:
send_content = f.read()
except Exception as e:
print(e)
new_socket.send(send_content)
print(send_content)
new_socket.close()
if __name__ == '__main__':
main()