Python 3中套接字编程中遇到TypeError: 'str' does not support the buffer interface的解决办法
转自:http://blog.csdn.net/chuanchuan608/article/details/17915959
目前正在学习python,使用的工具为python3.2.3。发现3x版本和2x版本有些差异,在套接字编程时,困扰了我很久,先将python核心编程书中的例子
代码如下:
服务器端:
# Echo server program
from socket import *
from time import ctime HOST = '' # Symbolic name meaning all available interfaces
PORT = 50007 # Arbitrary non-privileged port
BUFSIZE = 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(BUFSIZE)
if not data:
break
tcpCliSock.send(('[%s] %s' % (ctime(), data))) tcpCliSock.close()
tcpSerSock.close()
客户端
# Echo client program
from socket import* HOST = '127.0.0.1'
PORT = 50007 # The same port as used by the server
BUFSIZE = 1024
ADDR = (HOST, PORT) tcpCliSock = socket(AF_INET, SOCK_STREAM)
tcpCliSock.connect(ADDR)
while True:
data = input('> ')
if not data:
break
tcpCliSock.send(data)
data = tcpCliSock.recv(BUFSIZE)
if not data:
break
print(data) tcpCliSock.close()
报错:
TypeError:'str' does not support the buffer interface
找问题找了好久,在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 stringthat you need to use as a byte string, you need toencode() 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 b"" 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()
同时我看了一下python帮助文档:
Codec.encode(input[, errors])
Encodes the object input and returns atuple (output object, length consumed). Encoding converts a string object to abytes object using a particular character set encoding
Codec.decode(input[, errors])
Decodes the object input and returns atuple (output object, length consumed). Decoding converts a bytes objectencoded using a particular character set encoding to a string object.
input must be a bytes object or one whichprovides the read-only character buffer interface – for example, buffer objectsand memory mapped files.
套接字的成员函数send
socket.send(bytes[, flags]) 形参为字节类型
socket.recv(bufsize[, flags]) Receive datafrom the socket. The return value is abytes object representing the data received.
所以修正后代码如下:
服务器端:
# Echo server program
from socket import *
from time import ctime HOST = '' # Symbolic name meaning all available interfaces
PORT = 50007 # Arbitrary non-privileged port
BUFSIZE = 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(BUFSIZE).decode()
if not data:
break
tcpCliSock.send(('[%s] %s' % (ctime(), data)).encode()) tcpCliSock.close()
tcpSerSock.close()
客服端:
# Echo client program
from socket import* HOST = '127.0.0.1'
PORT = 50007 # The same port as used by the server
BUFSIZE = 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())
data = tcpCliSock.recv(BUFSIZE).decode()
if not data:
break
print(data) tcpCliSock.close()
运行结果: 达到预期
在使用这些函数时想当然去用,没有去查找帮助文档,没有弄清楚传参类型,可能是一个例题,没有注意这些,但是得吸取教训。
同样的在udp的情况下:修正过的
服务器端:
from socket import *
from time import ctime HOST = '';
PORT = 21546
BUFSIZE = 1024
ADDR = (HOST, PORT) udpSerSock = socket(AF_INET, SOCK_DGRAM)
udpSerSock.bind(ADDR) while True:
print('waiting for message...')
data, addr = udpSerSock.recvfrom(BUFSIZE)
udpSerSock.sendto(('[%s] %s' %(ctime(), data.decode())).encode(), addr)
print('...received from and returned to:', addr) udpSerSock.close()
客户端:
from socket import * HOST = 'localhost'
PORT = 21567
BUFSIZE = 1024
ADDR = (HOST, PORT) while True:
tcpCliSock = socket(AF_INET, SOCK_STREAM)
tcpCliSock.connect(ADDR)
data = input('> ')
if not data:
break
tcpCliSock.send(('%s\r\n' % data).encode())
data = tcpCliSock.recv(BUFSIZE).decode()
if not data:
break
print(data.strip())
tcpCliSock.close()
使用socketserver模块:
服务器端:
#TsTservss.py
from socketserver import TCPServer as TCP, StreamRequestHandler as SRH
from time import ctime HOST = ''
PORT = 21567
ADDR = (HOST, PORT) class MyRequestHandler(SRH):
def handle(self):
print('...connected from:', self.client_address)
self.wfile.write(('[%s] %s' %(ctime(), self.rfile.readline().decode())).encode()) tcpServ = TCP(ADDR, MyRequestHandler)
print('waiting for connection...')
tcpServ.serve_forever()
客户端:
from socket import * HOST = 'localhost'
PORT = 21567
BUFSIZE = 1024
ADDR = (HOST, PORT) while True:
tcpCliSock = socket(AF_INET, SOCK_STREAM)
tcpCliSock.connect(ADDR)
data = input('> ')
if not data:
break
tcpCliSock.send(('%s\r\n' % data).encode())
data = tcpCliSock.recv(BUFSIZE).decode()
if not data:
break
print(data.strip())
tcpCliSock.close()
Python 3中套接字编程中遇到TypeError: 'str' does not support the buffer interface的解决办法的更多相关文章
- python3使用套接字遇到TypeError: 'str' does not support the buffer interface如何解决
这是我查看的博客 http://blog.csdn.net/chuanchuan608/article/details/17915959 直接引用里面的关键语句: When you use clien ...
- python——TypeError: 'str' does not support the buffer interface
import socket import sys port=51423 host="localhost" data=b"x"*10485760 #在字符串前加 ...
- python编写telnet登陆出现TypeError:'str' does not support the buffer interface
python3支持byte类型,python2不支持.在python3中,telnet客户端向远程服务器发送的str要转化成byte,从服务器传过来的byte要转换成str,但是在python2不清楚 ...
- python3 TypeError: 'str' does not support the buffer interface in python
http://stackoverflow.com/questions/38714936/typeerror-str-does-not-support-the-buffer-interface-in-p ...
- Linux 套接字编程中的 5 个隐患(转)
本文转自IBM博文Linux 套接字编程中的 5 个隐患. “在异构环境中开发可靠的网络应用程序”. Socket API 是网络应用程序开发中实际应用的标准 API.尽管该 API 简单,但是开发新 ...
- (转载)Linux 套接字编程中的 5 个隐患
在 4.2 BSD UNIX® 操作系统中首次引入,Sockets API 现在是任何操作系统的标准特性.事实上,很难找到一种不支持 Sockets API 的现代语言.该 API 相当简单,但新的开 ...
- Linux 套接字编程中的 5 个隐患
http://www.ibm.com/developerworks/cn/linux/l-sockpit/ 在 4.2 BSD UNIX® 操作系统中首次引入,Sockets API 现在是任何操作系 ...
- Linux 套接字编程中要注意的细节
隐患 1.忽略返回状态 第一个隐患很明显,但它是开发新手最容易犯的一个错误.如果您忽略函数的返回状态,当它们失败或部分成功的时候,您也许会迷失.反过来,这可能传播错误,使定位问题的源头变得困难. 捕获 ...
- python TCP socket套接字编程以及注意事项
TCPServer.py #coding:utf-8 import socket #s 等待链接 #c 实时通讯 s = socket.socket(socket.AF_INET,socket.SOC ...
随机推荐
- 【设计模式 - 22】之策略模式(Strategy)
1 模式简介 在策略模式中,一个类的行为或其算法可以在运行时改变.策略模式定义了一系列算法,把它们一个个封装起来,并且使它们可以互相替换. 策略模式的优点: 1) 算法可以自由 ...
- python实战--Http代理服务器
打算好好深入研究下pytho的socket编程,那天看了这篇博文,http://www.apprk.com/archives/146,于是打算学习下,仿写了一下,发现写好还真不容易,中途出现很多问题, ...
- devm_kzalloc and kmalloc
Move resources allocated using unmanaged interface to managed devm interface So today let's talk abo ...
- POJ 1185 炮兵
是中国标题.大家都说水问题.但是,良好的1A它? 标题效果: 给出n*m的矩阵,当某个单元格有炮兵部队时它的上下左右两格(不包含斜着的方向)是这支部队的攻击范围.问在两支部队之间不可能相互攻击到的情况 ...
- PHPExcel的读取excel的操作
首先导入类库: require_once 'PHPExcel.php'; require_once 'PHPExcel\IOFactory.php'; require_once 'PHPExcel\R ...
- Btrace
http://www.iteye.com/topic/1005918 背景 周五下班回家,在公司班车上觉得无聊,看了下btrace的源码(自己反编译). 一些关于btrace的基本内容,可以看下我早起 ...
- [MySQL5.6] 一个简单的optimizer_trace示例
[MySQL5.6] 一个简单的optimizer_trace示例 前面已经介绍了如何使用和配置MySQL5.6中optimizer_trace(点击博客),本篇我们以一个相对简单的例子来跟踪op ...
- 以色列学生---debugger 构建
http://eli.thegreenplace.net/2011/01/23/how-debuggers-work-part-1 http://eli.thegreenplace.net/
- Qss All
/* * OOMidi application style sheet */QFrame#transportToolButtons{border: 0;spacing: 0;margin: 0;pad ...
- Java基础知识强化之网络编程笔记06:TCP之TCP协议发送数据 和 接收数据
1. TCP协议发送数据 和 接收数据 TCP协议接收数据:• 创建接收端的Socket对象• 监听客户端连接.返回一个对应的Socket对象• 获取输入流,读取数据显示在控制台• 释放资源 TCP协 ...