socket.send()错误:TypeError:需要一个类似字节的对象,而不是'str'

时间:2019-04-21 11:01:37

标签: python-3.x sockets import

我试图将python2代码转换为python3,但几乎结束了,但是出现错误!如果可以的话,请提供帮助。当我连接到服务器并键入要下载的文件名时,客户端出现问题: 客户代码:

import socket

def Main():

    host = '127.0.0.1'
    port = 9999

    s = socket.socket()
    s.connect((host, port))
    print("CONNECTED!")
    filename = input("Filename -> ")
    if filename != 'q':
        s.send(filename)
        data = s.recv(1024)
        if data[:6] == "EXISTS":
            filesize = (data[:6])
            message = input("File Exissts, "+str(filesize)+"Bytes, Download? (Y/N): ")
            if message == 'Y':
                s.send()
                f = open('new_'+filename, 'wb')
                data = s.recv(1024)
                totalRecv = len(data)
                f.write(data)
                while totalRecv<filesize:
                    data = s.recv(1024)
                    totalRecv += len(data)
                    f.write(data)
                    print((totalRecv/float(filesize))*100 + ("Downlaod Complete!"))
        else:
            print("File does not exists")
    s.close()
if __name__ == "__main__":
    Main()

问题是:

# python client1.py
CONNECTED!
Filename -> client.py
Traceback (most recent call last):
  File "client1.py", line 33, in <module>
    Main()
  File "client1.py", line 13, in Main
    s.send(str(filename))
TypeError: a bytes-like object is required, not 'str'

以及需要的服务器代码:

import socket
import threading
import os

def RetrFile(name, sock):
    filename = sock.recv(1024)
    if os.path.isfile(filename):
        sock.send("EXISTS" + str(os.path.getsize(filename)))
        userResponse = sock.recv(1024)
        if userResponse[:2] == 'OK':
            with open(filename, 'rb') as f:
                bytesToSend = f.read(1024)
                sock.send(bytesToSend)
                while bytesToSend != "":
                    bytesToSend = f.read(1024)
                    sock.send(bytesToSend)
    else:
        sock.send("ERR")
    sock.close()

def Main():
    host = '127.0.0.1'
    port = 9999
    s = socket.socket()
    s.bind((host,port))
    s.listen(5)

    print("Server Started...")
    while True:
        c, addr = s.accept()
        print("Client connected ip" + str(addr) + ">")
        t = threading.Thread(target=RetrFile, args=("retrThread", c ))
    s.close()

if __name__ == "__main__":
    Main()

首先我运行服务器脚本,然后运行客户端,服务器正常,但是在客户端上是问题所在

0 个答案:

没有答案