-
Notifications
You must be signed in to change notification settings - Fork 0
/
22-02-01-NetTrans.py
209 lines (169 loc) · 7.12 KB
/
22-02-01-NetTrans.py
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
import os
import json
import socket
import struct
import pyperclip
import tkinter as tk
from tkinter import filedialog
def input_file_path():
window = tk.Tk()
window.title('(^_^))')
window.geometry('220x20')
tk.Label(window, text='"Pls Select The File"').pack()
inpath = filedialog.askopenfilename(parent=window,
initialdir=os.getcwd(),
title="Please select a file:",
filetypes=[('all files', '.*')])
window.destroy()
return inpath
class NetworkServer:
SERVER_FILE_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'SERVER')
if not os.path.exists(SERVER_FILE_PATH):
os.makedirs(SERVER_FILE_PATH)
def __init__(self, ip, port):
self.ip = ip
self.port = port
def server_start(self):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((self.ip, self.port))
sock.listen(5)
print("The Server has been started...")
while True:
print("Waiting for a connection...")
conn, addr = sock.accept()
print(f"Connection established and the address is from {addr}")
while True:
# 获取消息类型
message_type = self.__recv_data(conn).decode('utf-8')
if message_type == 'close': # 四次挥手,空内容。
print("关闭连接")
break
# 文件:{'msg_type':'file', 'file_name':"xxxx.xx" }
# 消息:{'msg_type':'msg'}
message_type_info = json.loads(message_type)
if message_type_info['msg_type'] == 'msg':
data = self.__recv_data(conn)
pyperclip.copy(data.decode('utf-8'))
else:
file_name = message_type_info['file_name']
print("[*]接收文件信息...要保存到:", file_name)
print("--------------------------------")
self.__recv_file(conn, file_name)
print("\n--------------------------------")
print("[√]接收文件信息完成...")
conn.close()
sock.close()
@staticmethod
def __recv_data(conn, chunk_size=1024):
print("接收到消息...")
# 获取头部信息:数据长度
has_read_size = 0
bytes_list = []
print("[*]接收报文头消息...")
while has_read_size < 4:
chunk = conn.recv(4 - has_read_size)
has_read_size += len(chunk)
bytes_list.append(chunk)
header = b"".join(bytes_list)
data_length = struct.unpack('i', header)[0]
print("[√]接收报文头消息完成...")
# 获取数据
data_list = []
has_read_data_size = 0
print("[*]接收报文消息...")
print("--------------------------------")
while has_read_data_size < data_length:
size = chunk_size if (data_length - has_read_data_size) > chunk_size else data_length - has_read_data_size
chunk = conn.recv(size)
data_list.append(chunk)
has_read_data_size += len(chunk)
data = b"".join(data_list)
print(data.decode('utf-8'))
print("--------------------------------")
print("[√]接收报文消息完成...")
return data
def __recv_file(self, conn, save_file_name, chunk_size=1024):
save_file_path = os.path.join(self.SERVER_FILE_PATH, save_file_name)
# 获取头部信息:数据长度
has_read_size = 0
bytes_list = []
while has_read_size < 4:
chunk = conn.recv(4 - has_read_size)
bytes_list.append(chunk)
has_read_size += len(chunk)
header = b"".join(bytes_list)
data_length = struct.unpack('i', header)[0]
# 获取数据
file_object = open(save_file_path, mode='wb')
has_read_data_size = 0
while has_read_data_size < data_length:
size = chunk_size if (data_length - has_read_data_size) > chunk_size else data_length - has_read_data_size
chunk = conn.recv(size)
file_object.write(chunk)
file_object.flush()
has_read_data_size += len(chunk)
percent = round((int(has_read_data_size) / int(data_length)) * 100, 3)
print("\r文件总大小为:{}字节,已下载{}字节, 进度{}%".format(data_length, has_read_data_size, percent), end="")
file_object.close()
class NetworkClient:
def __init__(self, ip, port):
self.ip = ip
self.port = port
@staticmethod
def __send_data(conn, content):
data = content.encode('utf-8')
header = struct.pack('i', len(data))
conn.sendall(header)
conn.sendall(data)
@staticmethod
def __send_data_file(conn, file_path):
file_size = os.stat(file_path).st_size
header = struct.pack('i', file_size)
conn.sendall(header)
has_send_size = 0
file_object = open(file_path, mode='rb')
while has_send_size < file_size:
chunk = file_object.read(2048)
conn.sendall(chunk)
has_send_size += len(chunk)
percent = round((int(has_send_size) / int(file_size)) * 100, 3)
print("\r文件总大小为:{}字节,已发送{}字节, 进度{}%".format(file_size, has_send_size, percent), end="")
file_object.close()
def send_text(self):
client = socket.socket()
client.connect((self.ip, self.port))
print("[*]发送报文头信息...")
self.__send_data(client, json.dumps({"msg_type": "msg"}))
print("[√]发送报文头信息完成...")
__data = pyperclip.paste()
print("[*]发送文本信息...")
print("--------------------------------")
self.__send_data(client, __data)
print(__data)
print("--------------------------------")
print("[√]发送信息完成...")
self.__send_data(client, 'close')
client.close()
def send_close(self):
client = socket.socket()
client.connect((self.ip, self.port))
self.__send_data(client, "关闭")
print('发送关闭完成')
client.close()
def send_file(self):
file_path = input_file_path()
# file_name = file_path.rsplit(os.sep, maxsplit=1)[-1]
file_name = file_path.rsplit('/', maxsplit=1)[-1]
client = socket.socket()
client.connect((self.ip, self.port))
print("[*]发送报文头信息...")
self.__send_data(client, json.dumps({"msg_type": "file", 'file_name': file_name}))
print("[√]发送报文头信息完成...")
print("[*]发送文件信息...")
print("--------------------------------")
self.__send_data_file(client, file_path)
print("\n--------------------------------")
print("[√]发送文件完成...")
self.__send_data(client, 'close')
client.close()