欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

小记

程序员文章站 2022-09-14 10:22:43
问题TypeError: a bytes-like object is required, not 'str'(python3.5)在python核心编程第三版de网络编程的示例有错误示例代码(服务器端):HOST='localhost'PORT=1040BUFSIZ=1024ADDR=(HOST, ......

问题TypeError: a bytes-like object is required, not 'str'(python3.5)
在python核心编程第三版de网络编程的示例有错误

示例代码(服务器端):
HOST='localhost'
PORT=1040
BUFSIZ=1024
ADDR=(HOST,PORT)
tcpsock=socket(AF_INET,SOCK_STREAM)
tcpsock.bind(ADDR)
tcpsock.listen(5)
while True:
    print('waiting for connection...')
    tcpClient,addr=tcpsock.accept()
    print('....connected from :',addr)
    while 1:
        data=tcpClient.recv(BUFSIZ)
        if not data:
            break
        tcpClient.send('[%s] %s'%(bytes(ctime(),'utf-8'),data))
    tcpClient.close()
客户端:
from socket import *
HOST='localhost'
PORT=1040
BUFSIZ=1024
ADDR=(HOST,PORT)
tcpsock=socket(AF_INET,SOCK_STREAM)
tcpsock.connect(ADDR)
while 1:
    data=input('>')
    if not data:
        break
    tcpsock.send(data)
    data=tcpsock.recv(BUFSIZ)
    if not data:
        break
    print(data)
tcpsock.close()
按书上的代码跑不通的,原因是数据在网络是以bytes传输,需要把str转换成bytes
python可以直接通过bytes()方法转换

修正后(服务器端):
from socket import *
from time import ctime
HOST='localhost'
PORT=1040
BUFSIZ=1024
ADDR=(HOST,PORT)
tcpsock=socket(AF_INET,SOCK_STREAM)
tcpsock.bind(ADDR)
tcpsock.listen(5)
while True:
    print('waiting for connection...')
    tcpClient,addr=tcpsock.accept()
    print('....connected from :',addr)
    while 1:
        data=tcpClient.recv(BUFSIZ)
        if not data:
            break
        tcpClient.send('b[%s] %s'%(bytes(ctime(),'utf-8'),data))    #注意这行,加了b
    tcpClient.close()
客户端:
from socket import *
HOST='localhost'
PORT=1040
BUFSIZ=1024
ADDR=(HOST,PORT)
tcpsock=socket(AF_INET,SOCK_STREAM)
tcpsock.connect(ADDR)
while 1:
    data=input('>')
    if not data:
        break
    tcpsock.send((bytes(data.encode('utf-8'))))  #注意,把data转换成BYTES
    data=tcpsock.recv(BUFSIZ)
    if not data:
        break
    print(data.decode('utf-8'))    #注意,把bytes转换成str输出
tcpsock.close()