-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsocket_client.py
More file actions
34 lines (33 loc) · 1.14 KB
/
Copy pathsocket_client.py
File metadata and controls
34 lines (33 loc) · 1.14 KB
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
# socket客户端
import socket
import struct
import os
import json
def concect_upload_file(host,port,filename):
client = socket.socket()
ip_port = (host, int(port))
client.connect(ip_port)
buffer = 1024
header = { # 报头为dict类型
"filename": filename,
"filesize": 0,
}
file_path = os.path.join( header['filename'])
file_size = os.path.getsize(file_path)
header['filesize'] = file_size
header_json = json.dumps(header) # 报头序列化为json字符串
header_bytes = header_json.encode("utf-8") # 报头编码为bytes类型
client.send(struct.pack('i', len(header_bytes))) # 发送4个字节的报头大小
client.send(header_bytes) # 发送报头
client.send(struct.pack("i", file_size))
with open(filename, "rb") as f:
print("uploading...")
for line in f:
client.send(line)
print(f"{filename} upload ok")
client.close()
if __name__ == '__main__':
host=input("please input ip:")
port=input("please input port:")
filename = input("please intput filename:")
concect_upload_file(host,port,filename)