去中心化对等体2对等文件传输

时间:2019-02-10 08:46:11

标签: python-3.x

我正在尝试实现对等文件传输协议,遇到了此代码,但是当我将其移植到python 3.6时,出现此错误“类型错误,不需要字节类型的对象'str'”。请有人帮我解决这个问题。

server.py

! /usr/bin/python3.6

import subprocess
import socket
import sys
import os
import hashlib

HOST = 'localhost'
PORT = 8000

try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print('Server Created')
except OSError as e:
    print('Failed to create socket. Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
    sys.exit()

try:
    s.bind((HOST, PORT))
except OSError as e:
    print('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
    sys.exit()
print('Socket bind complete')

s.listen(1)
print('Server now listening')



while (1):
    conn, addr = s.accept()
    print('Connected with ' + addr[0] + ':' + str(addr[1]))
    reqCommand = conn.recv(1024)
    print('Client> %s' %(reqCommand))
    string = reqCommand.split(' ')
    if (reqCommand == 'quit'):
    break
    elif (reqCommand == 'lls'):
    toSend=""
    path = os.getcwd()
    dirs=os.listdir(path)
    for f in dirs:
        toSend=toSend+f+' '
    conn.send(toSend)
    #print path

    elif (string[1]== 'shortlist'):
    path = os.getcwd()
    command = 'find '+path+ ' -type f -newermt '+string[2]+' '+string[3]+ ' ! -newermt '+string[4]+' '+string[5]
    var = commands.getstatusoutput(command)
    var1 = var[1]
    var=var1.split('\n')
    rslt = ""
    for i in var:
        comm = "ls -l "+i+" | awk '{print $9, $5, $6, $7, $8}'"
        tup=commands.getstatusoutput(comm)
        tup1=tup[1]
        str=tup1.split(' ')
        str1=str[0]
        str2=str1.split('/')
        rslt=rslt+str2[-1]+' '+str[1]+' '+str[2]+' '+str[3]+' '+str[4]+'\n'
    conn.send(rslt)

    elif (string[1]=='longlist'):
    path = os.getcwd()
    var= commands.getstatusoutput("ls -l "+path+" | awk '{print $9, $5, $6, $7, $8}'")
    var1 = ""
    var1= var1+''+var[1]
    conn.send(var1)

    elif (string[0] == 'FileHash'):
    if(string[1]== 'verify'):
        BLOCKSIZE = 65536
        hasher = hashlib.sha1()
        with open(string[2], 'rb') as afile:
            buf = afile.read(BLOCKSIZE)
            while len(buf) > 0:
                hasher.update(buf)
                buf = afile.read(BLOCKSIZE)
        conn.send(hasher.hexdigest())
        print('Hash Successful')




    elif (string[1] == 'checkall'):
        BLOCKSIZE = 65536
        hasher = hashlib.sha1()

        path = os.getcwd()
        dirs=os.listdir(path)
        for f in dirs:
            conn.send(f)
            with open(f, 'rb') as afile:
                buf = afile.read(BLOCKSIZE)
                while len(buf) > 0:
                    hasher.update(buf)
                    buf = afile.read(BLOCKSIZE)
            conn.send(hasher.hexdigest())
            print('Hash Successful')



    else:
    string = reqCommand.split(' ')   #in case of 'put' and 'get' method
    if(len(string) > 1):
        reqFile = string[1]



        if (string[0] == 'FileUpload'):
                file_to_write = open(reqFile,'wb')
                si = string[2:]
                for p in si:
                    p = p + " "
                    print("User" + p)
                    file_to_write.write(p)
                while True:
                    data = conn.recv(1024)
                    print("User" + data)
                    if not data:
                        break
                    file_to_write.write(data)
                file_to_write.close()
                print('Receive Successful')
        elif (string[0] == 'FileDownload'):
            with open(reqFile, 'rb') as file_to_send:
                for data in file_to_send:
                        conn.sendall(data)
            print('Send Successful')
    conn.close()

s.close()

This is the error from the server.
Server Created
Socket bind complete
Server now listening
Connected with 127.0.0.1:37760
Client> b''
Traceback (most recent call last):
File "./server.py", line 36, in <module>
string = reqCommand.split(' ')
TypeError: a bytes-like object is required, not 'str'

这是我程序的客户端,但是有同样的问题。 client.py

#! /usr/bin/python3.6

import socket
import sys
import os
import hashlib

HOST = 'localhost'   #server name goes in here
PORT = 8000


def put(commandName):
    socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    socket1.connect((HOST, PORT))
    socket1.send(commandName)
    string = commandName.split(' ', 1)
    string = commandName.split(' ')
    inputFile = string[1]
    with open(inputFile, 'rb') as file_to_send:
    for data in file_to_send:
        socket1.sendall(data)
        print("Client users " + data)
        socket1.send(data)
    print('Upload Successful')
    socket1.close()
    return


def get(commandName):
    socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    socket1.connect((HOST, PORT))
    socket1.send(commandName(data. 'utf-8'))
    string = commandName.split(' ')
    inputFile = string[1]
    with open(inputFile, 'wb') as file_to_write:
    while True:
        data = socket1.recv(1024)
        if not data:
            break
        # print data
        file_to_write.write(data)
    file_to_write.close()
    print('Download Successful')
    socket1.close()
    return

def FileHash(commandName):
    string = commandName.split(' ')
    if string[1] == 'verify':
    verify(commandName)
    elif string[1] == 'checkall':
    checkall(commandName)


def verify(commandName):
    socket1=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    socket1.connect((HOST, PORT))
    socket1.send(commandName)
    hashValServer=socket1.recv(1024)

    string = commandName.split(' ')
    BLOCKSIZE = 65536
    hasher = hashlib.sha1()
    with open(string[2], 'rb') as afile:
    buf = afile.read(BLOCKSIZE)
    while len(buf) > 0:
        hasher.update(buf)
        buf = afile.read(BLOCKSIZE)
    hashValClient = hasher.hexdigest()
    print('hashValServer= %s', (hashValServer))
    print('hashValClient= %s', (hashValClient))
    if hashValClient == hashValServer:
    print('No updates')
    else:
    print('Update Available')

    socket1.close()
    return


def checkall(commandName):
    socket1=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    socket1.connect((HOST, PORT))
    socket1.send(commandName)

    string = commandName.split(' ')
    BLOCKSIZE = 65536
    hasher = hashlib.sha1()
    # f=socket1.recv(1024)

    while True:
    f=socket1.recv(1024)

    with open(f, 'rb') as afile:
        buf = afile.read(BLOCKSIZE)
        while len(buf) > 0:
            hasher.update(buf)
            buf = afile.read(BLOCKSIZE)
    hashValClient = hasher.hexdigest()
    hashValServer=socket1.recv(1024)

    print ('Filename =    %s', f)
    print('hashValServer= %s', (hashValServer))
    print('hashValClient= %s', (hashValClient))
    if hashValClient == hashValServer:
        print('No updates')
    else:
        print('Update Available')
    if not f:
        break



    socket1.close()
    return





def quit():
    socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    socket1.connect((HOST, PORT))
    socket1.send(commandName)
    socket1.close()
    return
def IndexGet(commandName):
    socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    socket1.connect((HOST, PORT))
    string = commandName.split(' ')
    if string[1] == 'shortlist':
    socket1.send(commandName)
    strng=socket1.recv(1024)
    strng=strng.split('\n')
    for f in strng:
        print(f)

    elif (string[1]=='longlist'):
    socket1.send(commandName)
    path=socket1.recv(1024)
    rslt=path.split('\n')
    for f in rslt[1:]:
        print(f)

    socket1.close()
    return

def serverList(commandName):
    socket1=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    socket1.connect((HOST, PORT))
    socket1.send(commandName)
    fileStr=socket1.recv(1024)
    fileList=fileStr.split(' ')
    for f in fileList[:-1]:
    print(f)

    socket1.close()
    return

msg = input('Enter your name: ')
while(1):
    print("\n")
    print("****************")
    print('Instruction')
    print('"FileUpload [filename]" to send the file the server ')
    print('"FileDownload [filename]" to download the file from the server ')
    print('"ls" to list all files in this directory')
    print('"lls" to list all files in the server')
    print('"IndexGet shortlist <starttimestamp> <endtimestamp>" to list the files modified in mentioned timestamp.')
    print('"IndexGet longlist" similar to shortlist but with complete file listing')
    print('"FileHash verify <filename>" checksum of the modification of the mentioned file.')
    print('"quit" to exit')
    print("\n")
    sys.stdout.write ('%s> ' %msg)
    inputCommand = sys.stdin.readline().strip()
    if (inputCommand == 'quit'):
    quit()
    break
    elif (inputCommand == 'ls'):
    path = os.getcwd()
    dirs = os.listdir(path)
    for f in dirs:
            print(f)
    elif (inputCommand == 'lls'):
    serverList('lls')

    else:
    string = inputCommand.split(' ', 1)
    if string[0] == 'FileDownload':
            get(inputCommand)
    elif string[0] == 'FileUpload':
            put(inputCommand)
    elif string[0] =='IndexGet':
        IndexGet(inputCommand)
    elif string[0] == 'FileHash':
        FileHash(inputCommand)

我将其扩展为无任何错误地传输文件,请新来的人可以帮助我。

This the error from the client
FileUpload closer.mp3
g> Traceback (most recent call last):
File "./client.py", line 193, in <module>
put(inputCommand)
File "./client.py", line 16, in put
socket1.send(commandName)
TypeError: a bytes-like object is required, not 'str'

1 个答案:

答案 0 :(得分:1)

即使需要字节数组,您仍在尝试发送字符串。 在'socket1.send(commandName)'中写socket1.send(commandName.encode('utf-8')

服务器端相同。

如果您无法弄清字节和字符串之间的区别,则应该重新考虑对加密货币进行编码。从一个简单的项目开始。