问题解决:TypeError: a bytes-like object is required, not 'str'

问题

import socket
import datetime

HOST = '0.0.0.0'
PORT = 3434

# AF_INET说明使用IPV4地址,SOCK_STREAM指明TCP
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)

while True:
    conn, addr = s.accept()
    print('Client %s connected!' % str(addr))
    dt = datetime.datetime.now()
    message = "Current time is " + str(dt)
    
    conn.send(message)
    
    print('Send: %s' % message)
    conn.close()

执行这个程序出现错误

TypeError: a bytes-like object is required, not 'str'

原因

Python2和Python3在Socket返回值解码上有区别,Python2读取到的数据是bytes

解决

只需要用上python的bytes和str两种类型转换的函数encode()、decode()即可!

str通过encode()方法可以编码为指定的bytes;

bytes通过decode()方法可以编码为指定的str。

更改后:

import socket
import datetime

HOST = '0.0.0.0'
PORT = 3434

# AF_INET说明使用IPV4地址,SOCK_STREAM指明TCP
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)

while True:
    conn, addr = s.accept()
    print('Client %s connected!' % str(addr))
    dt = datetime.datetime.now()
    message = "Current time is " + str(dt)
    
    conn.send(message.encode())
    
    print('Send: %s' % message)
    conn.close()

你可能感兴趣的:(问题解决,Python,问题解决)