1. 程式人生 > >TCP伺服器下載檔案 - python程式碼

TCP伺服器下載檔案 - python程式碼

    import socket
        
        def send_file_2_client(client_socket, client_addr):
        	
        	# 接收下載檔名
        	file_name = client_socket.recv(1024).decode("utf-8")
        	print("要下載的檔案是 %s " %  file_name)
        
        	file_contect = ""
        	# 開啟檔案
        	try:
        		f=
open(file_name, "rb") file_content = f.read() f.close() client_socket.send(file_content) except Exception as ret: print("沒有要下載的檔案 %s" % file_name) def main(): # 1.買個手機 tcp_server_socket = socket.socket(socket.
AF_INET, socket.SOCK_STREAM) # 2 插入手機卡 tcp_server_socket.bind(("",9996)) # 3 設定手機為監聽模式(SOCKET主動變成被動連線模式) tcp_server_socket.listen(128) # 4 等待接電話(等待客戶端的連線) client_socket, client_addr = tcp_server_socket.accept() send_file_2_client
(client_socket, client_addr) client_socket.close() #print("client_socket.close") tcp_server_socket.close() #print("server_socket.close") if __name__ == "__main__": main()