Python Socket TypeError: a bytes
《python核心编程》第三版,发现示例2-1代码返回错误
发现这里python3.5和Python2.7在套接字返回值解码上有区别。
先介绍一下 python bytes和str两种类型转换的函数encode(),decode()
str通过encode()方法可以编码为指定的bytes
反过来,如果我们从网络或磁盘上读取了字节流,那么读到的数据就是bytes。要把bytes变为str,就需要用decode()方法:
修正后:
tcp服务器
from socket import *
from time import ctime
HOST = ''
PORT = 22222
ADDR = (HOST, PORT)
BUFSIZ = 1024
tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)
while True:
print('waiting for connection...')
tcpCliSock, addr = tcpSerSock.accept()
print('...connected from: ', addr)
while True:
data = tcpCliSock.recv(BUFSIZ).decode()
if not data:
break
tcpCliSock.send(('[%s] %s' %(ctime(),data)).encode())
tcpCliSock.close()
tcpSerSock.close()
tcp客户端:
from socket import *
HOST = '127.0.0.1'
PORT = 22222
BUFSIZ = 1024
ADDR = (HOST, PORT)
tcpCliSock = socket(AF_INET, SOCK_STREAM)
tcpCliSock.connect(ADDR)
while True:
data = input('> ')
if not data:
break
tcpCliSock.send(data.encode('utf-8'))
data = tcpCliSock.recv(BUFSIZ)
if not data:
break
print(data.decode('utf-8'))
tcpCliSock.close()