Python Socket TypeError: a bytes-like object is required, not 'str' 错误提示

在学习socket编程时,遇到代码返回如下错误: TypeError: a bytes-like object is required, not ‘str‘ 
发现这里python3.5和Python2.7在套接字返回值解码上有区别。

首先可以明确,在python3中默认的编码方式是unicode。unicode 分为 utf-32(占4个字节),utf-16(占两个字节),utf-8(占1-4个字节),因此 utf-16就是现在最常用的unicode版本。 不过考虑到utf8省空间,在文件里存的还是utf-8。

书中示例

服务端

 1 #coding=utf-8
 2 #创建TCP服务器
 3 from socket import *
 4 from time import ctime
 5
 6 HOST=‘‘
 7 PORT=21567
 8 BUFSIZ=1024
 9 ADDR=(HOST,PORT)
10
11 tcpSerSock=socket(AF_INET,SOCK_STREAM) #创服务器套接字
12 tcpSerSock.bind(ADDR) #套接字与地址绑定
13 tcpSerSock.listen(5)  #监听连接,传入连接请求的最大数
14
15 while True:
16     print(‘waiting for connection...‘)
17     tcpCliSock,addr =tcpSerSock.accept()
18     print(‘...connected from:‘,addr)
19
20     while True:
21         data =tcpCliSock.recv(BUFSIZ)
22         #print(‘date=‘,data)
23         if not data:
24             break
25         tcpCliSock.send((‘[%s] %s‘ %(ctime(),data)))
26
27     tcpCliSock.close()
28 tcpSerSock.close()

客户端

 1 #coding=utf-8
 2
 3 from socket import *
 4
 5 HOST = ‘localhost‘ #  or ‘localhost‘
 6 PORT = 21567
 7 BUFSIZ = 1024
 8 ADDR=(HOST,PORT)
 9
10 tcpCliSock = socket(AF_INET,SOCK_STREAM)
11 tcpCliSock.connect(ADDR)
12
13 while True:
14     data = input(‘> ‘)
15     print(‘data=‘,data);
16     if not data:
17         break
18     tcpCliSock.send(data)
19     data = tcpCliSock.recv(BUFSIZ)
20     if not data:
21         break
22     print(data)
23
24 tcpCliSock.close() 

返回的错误提示: 
TypeError: a bytes-like object is required, not ‘str’

输入信息时,在客户端输入的是字符串(str类型),而代码中需要的是bytes类型,带着疑问去查原因,最终在StackOverflow上发现有人也出现同样的问题,且一个叫Scharron的人给出了解答:

In python 3, bytes strings and unicodestrings are now two different types. Since sockets are not aware of string encodings, they are using raw bytes strings, that have a slightly differentinterface from unicode strings.

So, now, whenever you have a unicode string that you need to use as a byte string, you need to encode() it. And whenyou have a byte string, you need to decode it to use it as a regular(python 2.x) string.

Unicode strings are quotes enclosedstrings. Bytes strings are being enclosed strings.

When you use client_socket.send(data),replace it by client_socket.send(data.encode()). When you get datausing data = client_socket.recv(512), replace it by data =client_socket.recv(512).decode()

因此,客户端传输信息时需要解码把  str类型  转换 bytes类型 用于传输,在接收到服务端信息后,需要进行编码,再把 bytes类型 转换成 str类型

以下为修改后的代码:

服务端

 1 #coding=utf-8
 2 #创建TCP服务器
 3 from socket import *
 4 from time import ctime
 5
 6 HOST=‘‘
 7 PORT=21567
 8 BUFSIZ=1024
 9 ADDR=(HOST,PORT)
10
11 tcpSerSock=socket(AF_INET,SOCK_STREAM) #创服务器套接字
12 tcpSerSock.bind(ADDR) #套接字与地址绑定
13 tcpSerSock.listen(5)  #监听连接,传入连接请求的最大数
14
15 while True:
16     print(‘waiting for connection...‘)
17     tcpCliSock,addr =tcpSerSock.accept()
18     print(‘...connected from:‘,addr)
19
20     while True:
21         data =tcpCliSock.recv(BUFSIZ).decode()
22         print(‘date=‘,data)
23         if not data:
24             break
25         tcpCliSock.send((‘[%s] %s‘ %(ctime(),data)).encode())
26
27     tcpCliSock.close()
28 tcpSerSock.close()

客户端

#coding=utf-8
#创建TCP服务器
from socket import *
from time import ctime

HOST=‘‘
PORT=21567
BUFSIZ=1024
ADDR=(HOST,PORT)

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()
        print(‘date=‘,data)
        if not data:
            break
        tcpCliSock.send((‘[%s] %s‘ %(ctime(),data)).encode())

    tcpCliSock.close()
tcpSerSock.close()

欢迎各位指正问题

Python Socket TypeError: a bytes-like object is required, not 'str' 错误提示

原文地址:https://www.cnblogs.com/Ames-Lakers/p/11105697.html

时间: 2024-10-09 09:46:08

Python Socket TypeError: a bytes-like object is required, not 'str' 错误提示的相关文章

【爬坑】Python 3.6 在 Socket 编程时出现类型错误 TypeError: a bytes-like object is required, not 'str'

1. 问题描述 Python 3.6 在 Socket 编程时出现错误如下 Traceback (most recent call last): File "F:/share/IdeaProjects/test/mypython/test/test10_tcpclient.py", line 17, in <module> sock.send(str) TypeError: a bytes-like object is required, not 'str' Process

Socket send() method throws TypeError: a bytes-like object is required, not &#39;str&#39;

python3 socket编程,发送data数据,会遇到需要bytes类型,而不是str字符串的错误 例如: import socket mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = socket.gethostbyname("www.google.com") mysock.connect(host, 80) message = "GET / HTTP/1.1\r\n\r\n"

python问题:TypeError: a bytes-like object is required, not &#39;str&#39;

源程序: import socket target_host = "www.baidu.com" # 127.0.0.1 target_port = 80 # 建立一个socket对象 client = socket.socket(socket.AF_INET,socket.SOCK_STREAM) # 创建TCP连接 # 连接客户端 client.connect((target_host,target_port)) client.send("GET / HTTP/1.1\r

python 3.5: TypeError: a bytes-like object is required, not &#39;str&#39;

出现该错误往往是通过open()函数打开文本文件时,使用了'rb'属性,如:fileHandle=open(filename,'rb'),则此时是通过二进制方式打开文件的,所以在后面处理时如果使用了str()函数,就会出现该错误,该错误不会再python2中出现. 具体解决方法有以下两种: 第一种,在open()函数中使用'r'属性,即文本方式读取,而不是'rb',以二进制文件方式读取,可以直接解决问题. 第二种,在open()函数中使用'rb',可以在使用之前进行转换,有以下实例,来自:htt

Python 3.5.2 TypeError: a bytes-like object is required, not &#39;str’问题解决方案

运行环境Mac  Python 3.5.2 Q: http_response = """\ HTTP/1.1 200 OK Hello, World! """ client_connection.sendall(http_response) TypeError: a bytes-like object is required, not 'str' 类型错误,需要的是一个byte类型,不是str类型 A: http_response = "

TypeError: a bytes-like object is required, not &#39;str&#39;

python bytes和str两种类型转换的函数encode(),decode() str通过encode()方法可以编码为指定的bytes 反过来,如果我们从网络或磁盘上读取了字节流,那么读到的数据就是bytes.要把bytes变为str,就需要用decode()方法 例如: date="12345"  #str类型 date.encode()  #转换为bytes类型 TypeError: a bytes-like object is required, not 'str' 原文

解决python mysql插入数据时报错:TypeError: %d format: a number is required, not str

今天在使用python爬取数据并将其写入mysql数据库时,使用该如下语句: cursor.execute( "insert into comments_p_spider(owner_id,from_name,content,create_time,score,comment_level) values(%d,%s,%s,%s,%f,%s)", (p_id,str(username), str(contentStr), str(create_time),float(score), st

python报&quot;TypeError: object of type &#39;Greenlet&#39; has no len()&quot;

TypeError: object of type 'Greenlet' has no len() 问题代码: gevent.joinall( gevent.spawn(func1), gevent.spawn(func2), gevent.spawn(func3), ) 应该为: gevent.joinall([ gevent.spawn(func1), gevent.spawn(func2), gevent.spawn(func3), ]) 总结:gevent.joinall()的参数应该为

python Socket网络编程 基础

内容概要 Socket介绍 Socket参数介绍 基本Socket实例 Socket实现多连接处理 通过Socket实现简单SSH 通过Socket实现文件传送 1. Socket介绍 Socket Families(地址簇) socket.AF_UNIX unix本机进程间通信  socket.AF_INET IPV4 socket.AF_INET6  IPV6 Socket Types socket.SOCK_STREAM  #for tcp socket.SOCK_DGRAM   #for