- str可以通过encode()编译成指定的byte
- byte可以通过decode()编译成指定的str
在python网络编程中出现一下报错:TypeError: a bytes-like object is required, not ‘str’
这是python3和python2在套接字上发送时编码和接收时解码的问题。
书中示例:
服务器:
# TCP服务器
from socket import *
from time import ctime
HOST =''
PORT = 6666
RUESIZ = 1024
addr = (HOST,PORT)
tcpSerSock = socket(AF_INET,SOCK_STREAM)
tcpSerSock.bind(addr)
tcpSerSock.listen(5)
while True:
print("fh")
tcpCliSock,addr = tcpSerSock.accept()
print(addr)
while True:
date = tcpCliSock.recv(RUESIZ)
if not date:
break
tcpCliSock.send('[%s] %s' %(ctime(),date))
tcpCliSock.close()
tcpSerSock.close()
客户端:
# TCP客户端
from socket import *
HOST = '127.0.0.1'
PORT = 6666
BUFSIZ =1024
add = (HOST,PORT)
tcpClisock = socket(AF_INET,SOCK_STREAM)
tcpClisock.connect(add)
while True:
date = input('> ')
if not date:
break
tcpClisock.send(date)
date = tcpClisock.recv(BUFSIZ)
if not date:
print('接收为空')
break
print(date.decode('utf-8'))
tcpClisock.close()
返回的错误提示:
TypeError: a bytes-like object is required, not ‘str’
所以需要对输入的数据和接收的数据进行转码。客户端传输信息时需要解码把 str类型 转换 bytes类型 用于传输,在接收到服务端信息后,需要进行编码,再把 bytes类型 转换成 str类型
因此用到上面的decode()和encode()函数。
最后变成:
服务器:
# TCP服务器
from socket import *
from time import ctime
HOST =''
PORT = 6666
RUESIZ = 1024
addr = (HOST,PORT)
tcpSerSock = socket(AF_INET,SOCK_STREAM)
tcpSerSock.bind(addr)
tcpSerSock.listen(5)
while True:
print("fh")
tcpCliSock,addr = tcpSerSock.accept()
print(addr)
while True:
date = tcpCliSock.recv(RUESIZ).decode() # decode()byte转为str 可以定为(utf8)
if not date:
break
tcpCliSock.send(('[%s] %s' %(ctime(),date)).encode()) #encode()str转为byte流
tcpCliSock.close()
tcpSerSock.close()
客户端:
# TCP客户端
from socket import *
HOST = '127.0.0.1'
PORT = 6666
BUFSIZ =1024
add = (HOST,PORT)
tcpClisock = socket(AF_INET,SOCK_STREAM)
tcpClisock.connect(add)
while True:
date = input('> ')
if not date:
break
tcpClisock.send(date.encode())
date = tcpClisock.recv(BUFSIZ)
if not date:
print('接收为空')
break
print(date.decode('utf-8'))
tcpClisock.close()