转自: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的解决办法的更多相关文章

  1. python3使用套接字遇到TypeError: 'str' does not support the buffer interface如何解决

    这是我查看的博客 http://blog.csdn.net/chuanchuan608/article/details/17915959 直接引用里面的关键语句: When you use clien ...

  2. python——TypeError: 'str' does not support the buffer interface

    import socket import sys port=51423 host="localhost" data=b"x"*10485760 #在字符串前加 ...

  3. python编写telnet登陆出现TypeError:'str' does not support the buffer interface

    python3支持byte类型,python2不支持.在python3中,telnet客户端向远程服务器发送的str要转化成byte,从服务器传过来的byte要转换成str,但是在python2不清楚 ...

  4. 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 ...

  5. Linux 套接字编程中的 5 个隐患(转)

    本文转自IBM博文Linux 套接字编程中的 5 个隐患. “在异构环境中开发可靠的网络应用程序”. Socket API 是网络应用程序开发中实际应用的标准 API.尽管该 API 简单,但是开发新 ...

  6. (转载)Linux 套接字编程中的 5 个隐患

    在 4.2 BSD UNIX® 操作系统中首次引入,Sockets API 现在是任何操作系统的标准特性.事实上,很难找到一种不支持 Sockets API 的现代语言.该 API 相当简单,但新的开 ...

  7. Linux 套接字编程中的 5 个隐患

    http://www.ibm.com/developerworks/cn/linux/l-sockpit/ 在 4.2 BSD UNIX® 操作系统中首次引入,Sockets API 现在是任何操作系 ...

  8. Linux 套接字编程中要注意的细节

    隐患 1.忽略返回状态 第一个隐患很明显,但它是开发新手最容易犯的一个错误.如果您忽略函数的返回状态,当它们失败或部分成功的时候,您也许会迷失.反过来,这可能传播错误,使定位问题的源头变得困难. 捕获 ...

  9. python TCP socket套接字编程以及注意事项

    TCPServer.py #coding:utf-8 import socket #s 等待链接 #c 实时通讯 s = socket.socket(socket.AF_INET,socket.SOC ...

随机推荐

  1. 修正android cocos2dx项目当点击属性时提示错误的问题

    近期在用cocos2dx 3.x版本号做android版本号的时候,出现点击project-属性-C/C++ builder的时候会提示 The currently displayed paye co ...

  2. SQL Server与Oracle对比学习:表的管理和组织

    http://blog.csdn.net/weiwenhp/article/details/8088979 我们知道数据库,顾名思义.最重要的东东就是管理数据,而数据在系统中主要是保存在表(table ...

  3. Linux I/O Scheduler--CFQ(上)图解

    http://blog.csdn.net/vanbreaker/article/details/8299491 http://doc.okbase.net/29060569/archive/46628 ...

  4. typename使用在模板中区分static成员和类型

    16.19 编写函数,接受一个容器的引用,打印容器中的元素,使用容器的size_type和size成员来控制打印元素的循环. 16.20 重写上一题的函数,使用begin和end返回的迭代器来控制循环 ...

  5. android开发的学习路线

    参考资料:千锋3G学院--课程大纲    http://www.mobiletrain.org 看了专业的培训机构的课程大纲,才知道,自己学习android的路途才刚刚开始!特此整理分享一下,希望能帮 ...

  6. windows mysql 中文乱码和中文录入提示太大错误的解决方法

    今天操作mysql的时候很郁闷,因为修改默认字符集搞了半天,终于弄成了(关于如何把windows的默认字符集设置成功,可以参看另一篇博文,最终在mysql中输入show variables like ...

  7. android开发之bitmap使用

    bitmap是android中重要的图像处理工具类,通过bitmap可以对图像进行剪切.旋转.缩放等操作,同时还可以指定格式和压缩质量保存图像文件. 一.拿到一个Bitmap对象 查看源码我们知道,B ...

  8. VC++ 响应回车键的2种方法

    众所周知,VC++响应回车键经常用的方法是利用 BOOL PreTranslateMessage(MSG* pMsg) 截取回车键消息,如: if (pMsg->message == WM_KE ...

  9. RedHat7搭建PHP开发环境(Zend Studio)

    下载Zend Studio # wget http://downloads.zend.com/studio-eclipse/13.0.1/ZendStudio-13.0.1-linux.gtk.x86 ...

  10. awk实用技巧

    awk '{sum+=$1} END {print "Sum = ", sum}' awk '{sum+=$1} END {print "Average = " ...