python - TypeError : a bytes-like object is required, not 'str' when writing to a file

标签 python python-3.x sockets

import socket

def Main():
    host = '127.0.0.1'
    port = 5001

    server = ('127.0.0.1',5000)

    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.bind((host, port))

    message = input("-> ")
    while message != 'q':
        s.sendto (message, server)
        data, addr = s.recvfrom(1024)
        print ('Received from server: ' + (data))
        message = input("-> ")
    s.close()

if __name__ == '__main__':
    Main()

当我运行此代码时,s.sendto (message, server)行会导致TypeError: a bytes-like object is required, not 'str'

您如何解决此类问题?我尝试搜索互联网,但找不到解决方案。

最佳答案

套接字读取和写入字节,而不是字符串(通常是套接字的属性,而不是python特定的实现选择)。这就是错误的原因。

字符串具有encode()方法,可将它们转换为字节对象。因此,与其编写my_text,不如将my_text.encode()写入您的套接字。

同样,当您读取套接字时,会得到一个类似字节的对象,可以在该对象上调用input_message.decode()将其转换为字符串

关于python - TypeError : a bytes-like object is required, not 'str' when writing to a file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60797514/

相关文章:

c - 如何正确使用套接字的 write() 函数?

python - 桌面开发语言是编译二进制还是脚本语言(windows)?

python - 为什么 Numpy 中的 0d 数组被视为标量?

python - Altair:如何根据最大值在面网格中对线条进行不同的样式设计?

python - 如何使用计划库运行异步函数?

python-3.x - Python - 比较 2 个单词并检查它们是否是变位词

python - 停止 PostgreSQL 将错误打印到 STDOUT

php - 如何在 localhost + ubuntu 中测试 PHP Socket 编程

c - Socket编程-C-选择连接

python - 如何在 Flask-SQLAlchemy 中按 id 删除记录