1. 程式人生 > 實用技巧 >HTML基本知識

HTML基本知識

廢話少說,直接上程式碼

 1 # 傳送端
 2 import socket
 3 
 4 def send_file(file_name,file_socket:socket.socket):
 5     try:
 6         f = open(file_name,'rb')
 7         while True:
 8             data = f.read(1024)
 9             if not data:
10                 break
11             file_socket.send(data)
12         f.close()
13 except FileNotFoundError: 14 print(f'沒有找到{file_name}') 15 16 if __name__ == '__main__': 17 try: 18 file_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 19 file_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,True) 20 ip = str(input('請輸入接收端IP:
')) 21 port = int(input('請輸入接收端埠號:')) 22 file_socket.connect((ip,port)) 23 path = r'%s' % input('請輸入檔案所在資料夾:') 24 print(file_socket.recv(1024).decode('gbk')) 25 file_name = str(input()) 26 file_socket.send(file_name.encode('gbk')) 27 send_file(path + file_name,file_socket)
28 except ConnectionResetError: 29 print('接收端斷開連線')
 1 # 接收端
 2 import socket,os
 3 
 4 def dowload(file_name,file_socket:socket.socket):
 5     os.chdir('D:/Python檔案傳輸/')
 6     f = open(file_name,'wb')
 7     while True:
 8         data = file_socket.recv(1024)
 9         if not data:
10             print('接收完畢!')
11             break
12         f.write(data)
13     f.close()
14 
15 if __name__ == '__main__':
16     try:
17         file_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
18         file_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,True)
19         file_socket_port = int(input('請輸入埠號:'))
20         file_socket.bind(('',file_socket_port))
21         print('成功啟動,等待連線。。。')
22         file_socket.listen(1)
23         f_socket, f_addr = file_socket.accept()
24         print(f'建立連線{f_addr}')
25 
26         f_socket.send('請輸入檔名'.encode('gbk'))
27         file_name = f_socket.recv(1024)
28         dowload(file_name,f_socket)
29         f_socket.close()
30         file_socket.close()
31     except ConnectionResetError:
32         print('傳送端已斷開連線')
33     except UnicodeDecodeError:
34         print('檔案編碼錯誤,請檢查檔案格式是否正確(暫不支援exe檔案)')