TCP套接字繫結雙埠傳輸檔案(python)

木子昭發表於2017-08-04

服務端程式碼

import socket


# 建立tcp服務套接字
def main():
    tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    tcp_server_socket_for_file_name = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print("1.套接字建立完畢...") 
    # 繫結埠號
    tcp_server_socket.bind(("",40000))
    tcp_server_socket_for_file_name.bind(("",50000))
    print("2.埠繫結完畢")
    # 轉為被動模式

    tcp_server_socket.listen(128)
    tcp_server_socket_for_file_name.listen(128)
    print("3.被動模式轉換完畢")
    # 接收到新的連線則建立服務套接字

    client_socket, client_addr = tcp_server_socket.accept()
    client_socket_for_file_name, client_addr_for_file_name = tcp_server_socket_for_file_name.accept()
    print("4.拆包完畢....")
    file_name = client_socket_for_file_name.recv(1024)
    print("接收到的file_name為:%s"%file_name)
    file_name = file_name.decode("utf-8")
    f = open(file_name,"wb+")

    while True:
        content = client_socket.recv(50)
        if (content):
            print("準備寫入",content)
            f.write(content)
            print("已經寫入",content)

        else:
            f.close()
            break
    print("執行完成")
if __name__ == "__main__":
    main()


客戶端程式碼

import socket
import os

g_the_dir_list = list()

# 顯示目錄
def display_dir():
    print("當前目錄為:")
    for i, the_dir in enumerate(g_the_dir_list):
        print(i, the_dir)

def main():
    global g_the_dir_list
    # 讀取當前目錄下檔案列表
    g_the_dir_list = os.listdir(os.getcwd())

    # 建立客戶端socket
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # 建立第二個socket(負責傳送檔名)
    client_socket_for_file_name = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # 建立連線
    server_ip = input("請輸入服務端ip(佔用埠40000與50000)")
    client_socket.connect((server_ip, 40000))
    client_socket_for_file_name.connect((server_ip, 50000))

    # 顯示當前目錄下檔案列表
    display_dir()

    file_index = int(input("請輸入需要傳送的檔案序號:"))
    # 開啟檔案並通過socket.send傳送
    client_socket_for_file_name.send(g_the_dir_list[file_index].encode("utf-8"))
    f = open(g_the_dir_list[file_index], "rb")
    while True: 
        content = f.read(1024)
        if (content):
            client_socket.send(content)
        else:
            print("傳送完畢!")
            f.close()
            break
if __name__ == "__main__":
    main()


相關文章