本文实例讲述了python使用socket实现的传输demo。分享给大家供大家参考,具体如下:socket传
本文实例讲述了python使用socket实现的传输demo。分享给大家供大家参考,具体如下:
socket传输,客户端代码
import socket
def main():
tcp_client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 服务器位于本机 9999
tcp_client_socket.connect( ("192.168.27.72", 9999) )
# 告诉服务器,我要下载哪一个文件
file_name = input("请输入要下载的文件名:")
tcp_client_socket.send(file_name.encode("utf-8"))
temp = tcp_client_socket.recv(1024)
print(temp)
file_length = int(temp.decode("utf-8"))
# 接收数据 字节
recv_data = tcp_client_socket.recv(file_length)
# 得到数据,需要将数据写入文件
if recv_data:
# f = open("new_" + file_name, "wb")
# try:
# f.write(recv_data)
# except Exception as result:
# print("写入文件错误")
# finally:
# f.close()
with open("new_" + file_name, "wb") as f:
f.write(recv_data)
tcp_client_socket.close()
if __name__ == '__main__':
main()
服务端代码:
import socket
def main():
#1创建套接字
tcp_server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#2绑定本地信息bind
tcp_server_socket.bind(('',9999))
#3让默认的套接字由主动变为被动listen ????
tcp_server_socket.listen(128)
#4等待别人的电话到来(等待客户端的链接 accept)
new_client_socket, client_addr = tcp_server_socket.accept()
#5调用发送文件函数,完成为客户端服务
rece_data = new_client_socket.recv(1024)
file_name = rece_data.decode('utf-8')
try:
f = open(file_name, 'rb')
content = f.read()
file_length = len(content)
print(file_length)
new_client_socket.send(str(file_length).encode('utf-8')) #????1两个发送第二个执行快了怎么办?
new_client_socket.send(content)
except Exception as f:
print('文件打开失败')
# 6关闭套接字
new_client_socket.close()
tcp_server_socket.close()
if __name__ == '__main__':
main()
python
socket
传输
TCP协议