首页 > 解决方案 > 向客户端发送字符串 - 接收 TypeError

问题描述

我正在尝试向客户端发送图像,因此我已将图像转换为字符串。这是我的代码:

def send_image_to_client(file_name, client_socket):
    """sends an image to the client"""

    with open(file_name, "rb") as im:
        string = base64.b64encode(im.read())  # convert image into a string
        print "sending image..."
        client_socket.send(string)

    return

出于某种原因,我收到以下错误:

send() 参数 1 必须是字符串或缓冲区,而不是 None

我究竟做错了什么?

此示例显示相同的错误:

def show_content(directory, client_socket):
"""displays the content of a given directory"""
import glob
files_list = glob.glob(directory+"\*.*")
files_list[-1] += "--"
for address in files_list:
    if address:
        send_response_to_client(address+"*", client_socket)
return

标签: python

解决方案


上面的代码确实是您正在尝试的代码,或者您在将其发布到此处之前已经进行了任何清理?你可以试试这个——

with open(file_name, "rb") as im:
    string = base64.b64encode(im.read())  # convert image into a string
    print "sending image..."
    print(type(string))
    if (string):
        client_socket.send(string.encode())
    else:
        print("No Data received from base64encode")
return

推荐阅读