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 ...
随机推荐
- Hibernate查询方法总结
1. HQL查询 HQL是Hiberante官方推荐的Hibernate检索方式,它使用类似SQL的查询语言,以面向对象的方式从数据库中查询.可以使用HQL查询具有继承.多态和关 联关系的数据.在检索 ...
- android的消息处理机制(图+源码分析)——Looper,Handler,Message
android源码中包含了大量的设计模式,除此以外,android sdk还精心为我们设计了各种helper类,对于和我一样渴望水平得到进阶的人来说,都太值得一读了.这不,前几天为了了解android ...
- uva 167 - The Sultan's Successors(典型的八皇后问题)
这道题是典型的八皇后问题,刘汝佳书上有具体的解说. 代码的实现例如以下: #include <stdio.h> #include <string.h> #include < ...
- android 67 生成和解析xml
生成xml: package com.itheima.createxml; import java.io.File; import java.io.FileNotFoundException; imp ...
- ServletContext对象--三大域对象
Servlet三大域对象的应用 request.session.application(ServletContext) ServletContext是一个全局的储存信息的空间,服务器开始就存在,服务器 ...
- XC文件管理器(Android应用)
XC文件管理器,是基于Android4.4开发的一个方便易用的文件管理器,具有文件的目录管理和文件的管理,主要包括文件的新建.删除.重命名.复制,移动剪切以及文件详情查看等文件和目录的功能,同时支持文 ...
- Jquery调用从ashx文件返回的jsonp格式的数据处理实例
开发环境:vs2010+jquery-1.4.min.js 解决问题:网上代码比较少,好多调试不通,返回数据不用json而用jsonp主要考虑解决跨域问题 开发步骤:打开VS2010,新建一web站点 ...
- 自己封装的工具类,使用原生SwipeRefreshLayout+RecycleView实现下拉刷新和加载更多
实现SwipeRefreshLayout+RecycleView实现刷新 在你的xml文件里写上如下代码: <android.support.v4.widget.SwipeRefreshLayo ...
- Unity3D中读取CSV文件
直接上代码 Part1: using UnityEngine; using System.IO; using System.Collections.Generic; public class CSV ...
- Linux中Curl命令couldn't connect to host解决方案 php操作Curl(http,https)无法获取远程数据解决方案
本人在做百度账户第三方登录接口,获取百度token,利用php操作curl post方式发送请求token,出现couldn't connect to host错误.经过调试测试,最后终于成功.回头写 ...