1. 程式人生 > >python中socket傳輸demo

python中socket傳輸demo

socket傳輸,客戶端程式碼

import socket

def main():
    tcp_client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # 伺服器位於本機  9999
    tcp_client_socket.connect( ("192.168.27.72", 9999) )


    #  告訴伺服器,我要下載哪一個檔案
    file_name = input("請輸入要下載的檔名:")
    tcp_client_socket.send(file_name.encode("utf-8"))
    temp = tcp_client_socket.recv(1024)
    print(temp)
    file_length = int(temp.decode("utf-8"))
    # 接收資料  位元組
    recv_data = tcp_client_socket.recv(file_length)
    # 得到資料,需要將資料寫入檔案

    if recv_data:

        # f = open("new_" + file_name, "wb")
        # try:
        #     f.write(recv_data)
        # except Exception as result:
        #     print("寫入檔案錯誤")
        # finally:
        #     f.close()

        with open("new_" + file_name, "wb") as f:
            f.write(recv_data)



    tcp_client_socket.close()


if __name__ == '__main__':
    main()

服務端程式碼:

import socket

def main():
    #1建立套接字
    tcp_server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

    #2繫結本地資訊bind
    tcp_server_socket.bind(('',9999))

    #3讓預設的套接字由主動變為被動listen  ????
    tcp_server_socket.listen(128)

    #4等待別人的電話到來(等待客戶端的連結 accept)
    new_client_socket, client_addr = tcp_server_socket.accept()

    #5呼叫傳送檔案函式,完成為客戶端服務
    rece_data = new_client_socket.recv(1024)
    file_name = rece_data.decode('utf-8')

    try:
        f = open(file_name, 'rb')
        content = f.read()
        file_length = len(content)
        print(file_length)
        new_client_socket.send(str(file_length).encode('utf-8'))     #????1兩個傳送第二個執行快了怎麼辦?
        new_client_socket.send(content)
    except Exception as f:
        print('檔案開啟失敗')
    # 6關閉套接字
    new_client_socket.close()
    tcp_server_socket.close()

if __name__ == '__main__':
    main()