python3 的socket 文件传输 二进制

实现了python3 的socket 文件传输

服务端

其中服务端需要在服务端一直保持运行状态

from socket import *
import os
import shlex, subprocess

serverPort = 12000
serverSocket = socket(AF_INET,SOCK_STREAM)#新建
serverSocket.bind(('',serverPort))
serverSocket.listen(1)



while True:
    # 脚本可以接受文件
    print ('The server is ready to receive')
    try:
        #建立链接
        connectionSocket, addr = serverSocket.accept()

        sentence = connectionSocket.recv(1024).decode()
        connectionSocket.send(bytes("connection start!",'utf-8'))
        # 若果发送的是链接建立请求那么建立链接,否则重新等待新的链接建立请求
        if sentence=="start of transmission":
            # 这次传输的是文件名字
            name = connectionSocket.recv(1024).decode()
            connectionSocket.send(bytes("filename ACK",'utf-8'))

            print(name)
            f=open("copy_"+name,"wb")
            
        else :
            print("error in connection setting!")
            continue
        counter=1
        while True:
            try:
                # 接受文件1024 bytes
                data = connectionSocket.recv(1024)
                # 文件结束标志
                if data==b"00001111":
                    print("end of file")
                    connectionSocket.send(bytes("continue",'utf-8'))
                    break
                else:
                    #写入文件中
                    f.write(data)
                    
                    print("this is the "+str(counter))
                    connectionSocket.send(bytes("continue",'utf-8'))
                    counter=counter+1
            # 键盘中断
            except KeyboardInterrupt:
                print("file transmission with crtl c!")
                pass
            
        # 文件写入完成信息
        print("close file!")
        f.close()
        print("close file success!")
        connectionSocket.close()
        # 键盘退出
    except KeyboardInterrupt:
        connectionSocket.close()
        exit("keyboard Interrupt")

客户端

封装成一个函数,对主机ip,服务器端口号,文件名字调用即可,十分方便

from socket import *
import os
def file_send(serverName,serverPort,name):
    # serverName ='192.168.43.87'

    # serverPort = 12000
    clientSocket = socket(AF_INET, SOCK_STREAM)#新建链接
    clientSocket.connect((serverName,serverPort))

    # 建立链接
    print("initial connection")
    start_sentence="start of transmission"
    clientSocket.send(bytes(start_sentence,'utf-8'))
    modifiedSentence = clientSocket.recv(2048).decode()
    # 服务端同意则开始传输文件名
    if modifiedSentence=="connection start!":
        print("server allow the connection!")
    else :
        print("start error!")

    #发送文件名字
    # name="test_1.png"
    print("sending file name")
    clientSocket.send(bytes(name,'utf-8'))
    modifiedSentence = clientSocket.recv(2048).decode()
    if modifiedSentence=="filename ACK":
        print("server ACK the file name")

    #发送文件
    counter=1
    try:
        files=open(name, "rb")
        while True :
            data=files.read(1024)
            # 如果读取结束那么就发送b"00001111"表示结束
            if data==b"":
                clientSocket.send(b"00001111")
                break
            else:
                clientSocket.send(data)
            
                print("waiting "+str(counter)+" response")
                modifiedSentence=clientSocket.recv(1024).decode()
                print("get "+str(counter)+" response")
                
                counter=counter+1
    except :
        pass


    # end_sentence="end of transmission"
    # clientSocket.send(bytes(end_sentence,'utf-8'))
    print("end transmisson success!")
    clientSocket.close()#关闭

file_send('192.168.43.87',12000,"test_1.png")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值