파이썬, 소켓 통신 프로그램, 파일 업로드의 예

업로드 된 파일을 수신하려면 file_send.py에서 file_receive.py 파일을 업로드하는 file_receive.py과 file_send.py 프로그램을 작성, 패키지에 지정하여 작성

# file_receive.py의 
수입
소켓, 서브 프로세스, OS BASE_DIR = os.path.dirname (os.path.abspath ( __file__ )) SK = socket.socket () 어드레스 = ( ' 127.0.0.1 ' , 8001 ) sk.bind (어드레스 ) sk.listen ( 3 ) CONN, ADDR = sk.accept () 는 FileInfo = conn.recv (1024 ) 파일명, 파일 크기 = STR (에서는 FileInfo, ' UTF8 ' ) .split ( " | " ) # 파일명 = STR (파일명 'UTF8') #파일 크기 = INT (STR (파일 크기 'UTF8')) 경로 = os.path.join (BASE_DIR, ' file_recv ' , 파일명) F = 개방 (경로 " (WB)는 ' ) has_received = 0 동안 has_received! = INT (파일 크기) : 데이터 = conn.recv (1024 ) f.write (데이터) has_received + = LEN (데이터) f.close () 인쇄 ( ' ' ) sk.close ()
# file_send.py의 
수입 소켓, 운영 체제 
BASE_DIR = os.path.dirname (os.path.abspath ( __FILE__ )) 
SK = socket.socket () 
주소 = ( ' 127.0.0.1 ' , 8001 ) 
sk.connect (주소) 
파일 이름 = 입력 ( " 입력 해주십시오 파일 이름 : " ) 
경로 = os.path.join (BASE_DIR, 파일 이름) 
파일 크기 = os.stat (경로) .st_size 
에서는 FileInfo = ' %의 | %의 ' % (파일 이름, STR (파일 크기)) 
sk.sendall (바이트 (에서는 FileInfo, 'UTF8 ' )) 

F = 개방 (경로 ' RB ' ) 

has_sent = 0
 동안 ! = has_sent : INT (파일 크기) 
    데이터 = f.read (1024 ) 
    sk.sendall (데이터) 
    has_sent + = LEN (데이터)의 

출력 ( ' 잘! ' ) 
f.close () 
sk.close를 ()

파일이 실행되면, 현재 경로에 file_recv 패키지에 업로드 업로드 file_send.py의 test.png 파일을 달성했다.

추천

출처www.cnblogs.com/iceberg710815/p/12034518.html