TypeError:需要一个类似字节的对象,而不是'str' [英] TypeError: a bytes-like object is required, not 'str'

查看:239
本文介绍了TypeError:需要一个类似字节的对象,而不是'str'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试建立客户端-服务器模型,这是python网络编程的新手,但我陷入了一个错误,该错误指出以下内容:-

I am trying to make a client-server model, being new to python network programming I am stuck on an error which states the following:-

tcpCliSoc.send('[%s]%s'%(bytes(ctime(),'utf_8'),data))TypeError:需要一个类似字节的对象,而不是'str'

tcpCliSoc.send('[%s] %s' % (bytes(ctime(), 'utf_8'), data)) TypeError: a bytes-like object is required, not 'str'

这是服务器和客户端的实现

Here is the Server and client implementation

TCP服务器实现

from socket import *  
from time import ctime

HOST = ''  
PORT = 21572  
ADDR = (HOST, PORT)  
BUFFSIZE = 1024  

tcpSerSoc = socket(AF_INET, SOCK_STREAM)

tcpSerSoc.bind(ADDR)
tcpSerSoc.listen(5)

while True:  
    print("waiting for connection......")  
    tcpCliSoc, addr = tcpSerSoc.accept()  
    print("connected from", addr)  

    while True:  
        data = tcpCliSoc.recv(BUFFSIZE)
        if not data:
            break
        tcpCliSoc.send('[%s] %s' % (bytes(ctime(), 'utf_8'), data))
    tcpCliSoc.close()
tcpSerSoc.close()

TCP客户端实现

from socket import *

__author__ = 'Lamer'

HOST = 'localhost'
PORT = 21572
ADDR = (HOST, PORT)
BUFFSIZE = 1024

tcpCliSoc = socket(AF_INET, SOCK_STREAM)
tcpCliSoc.connect(ADDR)

while True:
    data = input('>')
    if not data:
        break
    tcpCliSoc.send(data.encode())
    data = tcpCliSoc.recv(BUFFSIZE)
    if not data:
        break
    print(data.decode(encoding='utf-8'))

tcpCliSoc.close()

推荐答案

字符串插值创建的是字符串,而不是字节对象:

The string interpolation is creating a string, not a bytes object:

>>> '%s foo' % b'bar'
"b'bar' foo"

(请注意,结果的类型为str,并且其中包含'b'并插入了一些您可能不需要的引号).

(Notice that the result is of type str -- And it has a 'b' and some quotes inserted in it that you probably don't want).

您可能想用字节插入字节:

You probably want to interpolate bytes with bytes:

>>> b'%s foo' % b'bar'
b'bar foo'

或者,在您的代码中:

tcpCliSoc.send(b'[%s] %s' % (bytes(ctime(), 'utf_8'), data))

这篇关于TypeError:需要一个类似字节的对象,而不是'str'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆