python3 类型Type str doesn't support the buffer API?
饿,代码是抄书的,书是《python基础教程》,由于书的代码是python2,的,但是我又想学python3,所以自己改了一下代码,遇到了一些问题 先补上图片
#!/usr/bin/env python3
__author__ = 'tcstory'
from asyncore import dispatcher
from asynchat import async_chat
import socket, asyncore
PORT=5005
NAME='TestChat'
class EndSession(Exception): pass
class CommandHandler:
'''
Simple command handler similar to cmd.Cmd from the standard library
'''
def unknown(self, session, cmd):
'Respond to an unknown command'
session.push('Unkonw command: {0}\r\n'.format(cmd).encode())
def handle(self, session, line):
'Handle a received line from a given session'
if not line.strip():
return
#Split off the command
parts = line.split(' ', 1)
cmd = parts[0]
try:
line=parts[1].strip()
except IndexError:
line=''
#Try to find a handler
meth=getattr(self,'do_'+cmd,None)
try:
#Assume it's callable
meth(session,line)
except TypeError:
#If it isn't ,respond to the unknown command
self.unknown(session,cmd)
class Room(CommandHandler):
'''
A generic environment that may contain one or more users(sessions).it takes care of basic command handling and broadcasting.
'''
def __init__(self,server):
self.server=server
self.sessions=[]
def add(self,session):
'A session(user) has entered the room'
self.sessions.append(session)
def remove(self,session):
'A session (user) has left the room'
self.sessions.remove(session)
def broadcast(self,line):
'Send a line to all sessions in the room'
for session in self.sessions:
session.push(line.encode())
def do_logout(self,session,line):
'Respond to the logout command'
raise EndSession
class LoginRoom(Room):
'''
A room meant for a single person who has just connected
'''
def add(self,session):
Room.add(self,session)
#When a user enters,greet him/her
self.broadcast('Welcome to {0}\r\n'.format(self.server.name))
def unknown(self, session, cmd):
#All unknown commands (anything except login or logout)
#results in a prodding
session.push('Please log in\nUse "login <nick>"\r\n'.encode())
def do_login(self,session,line):
name=line.strip()
#Make sure the user has entered a name
if not name:
session.push('Please enter a name\r\n'.encode())
#Make sure that the name isn't in use
elif name in self.server.users:
session.push('The name {0} is taken.\r\n'.format(name).encode())
session.push('Please try again.\r\n'.encode())
else:
#The name is OK,os it is stored in the session.and
#the user is moved into the main room
session.name=name
session.enter(self.server.main_room)
class ChatRoom(Room):
'''
A room meant for multiple users who can chat with the others in the room
'''
def add(self,session):
#Notify everyone that a new user has entered
self.broadcast('{0} has entered the room.\r\n'.format(session.name))
self.server.users[session.name]=session
Room.add(self,session)
def remove(self,session):
Room.remove(self,session)
#Notify everyone that a user has left
self.broadcast('{0} has left the room.\r\n'.format(session.name))
def do_say(self,session,line):
self.broadcast('{0}: '+line+'\r\n'.format(session.name))
def do_look(self,session,line):
'Handles the look command,used to see who is in a room'
session.push('The following are in this room:\r\n'.encode())
for other in self.sessions:
session.push('{0}\r\n'.format(other.name).encode())
def do_who(self,session,line):
'Handles the who command ,used to see who is logged in'
session.push('The following are logged in:\r\n'.encode())
for name in self.server.users:
session.push('{0}\r\n'.format(name))
class LogoutRoom(Room):
'''
A simple room for a single user.Its sole purpose is to remove the user's name from the server
'''
def add(self,session):
#When a session (user) enters the LogoutRoom it is deleted
try:
del self.server.users[session.name]
except KeyError:
pass
class ChatSession(async_chat):
'''
A single session,which takes care of the communication with a single user
'''
def __init__(self,server,sock):
# async_chat.__init__(self,sock)
super().__init__(sock)
self.server=server
self.set_terminator('\r\n')
self.data=[]
self.name=None
#All sessions begin in a separate LoginRoom
self.enter(LoginRoom(server))
def enter(self,room):
# Remove self from current room and add self to next room....
try:
cur=self.room
except AttributeError:pass
else:
cur.remove(self)
self.room=room
room.add(self)
def collect_incoming_data(self, data):
self.data.append(data)
def found_terminator(self):
line=''.join(self.data)
self.data=[]
try:
self.room.handle(self,line)
except EndSession:
self.handle_close()
def handle_close(self):
async_chat.handle_close(self)
self.enter(LogoutRoom(self.server))
class ChatServer(dispatcher):
'''
A chat server with a single room
'''
def __init__(self,port,name):
super().__init__()
# dispatcher.__init__(self)
self.create_socket(socket.AF_INET,socket.SOCK_STREAM)
self.set_reuse_addr()
self.bind(('',port))
self.listen(5)
self.name=name
self.users={}
self.main_room=ChatRoom(self)
def handle_accept(self):
conn,addr=self.accept()
ChatSession(self,conn)
if __name__=='__main__':
# www.iplaypy.com 百度搜:玩蛇网
s=ChatServer(PORT,NAME)
try:
asyncore.loop()
except KeyboardInterrupt:
print()
这是stackoverflow上的问题,老外帮我改了一下,可能阅读效果更好
http://stackoverflow.com/questions/24928908/python3-type-str-doesnt-support-the-buffer-api
玩蛇网文章,转载请注明出处和文章网址:https://www.iplaypy.com/wenda/wd19555.html
相关文章 Recommend
- • 使用python的类报错TypeError: say() takes exactly 2 argu
- • type()方法不是python最好的判断变量类型方法吗?
- • python soap client 错误: suds.TypeNotFound: Type not f
- • Python3.0版本做web可以吗?
- • Python判断变量类型isinstance()与type()不同之处是什
- • Python对于HTTP应用反馈mime-type列表?
- • python3.3有哪些特别好用的模块
- • Python str函数与repr函数两都有何不同
- • Python3 在使用traceback.format_exc()的时候遇到 Unicod
- • Python 文件添加列表数据后TypeError原因
- • 求大神帮看下python代码中type作用是什么
- • 求python大牛帮看看ctypes.string_at的问题
您现在的位置: 玩蛇网首页 > Python问题解答 > 正文内容
我要分享到:
必知PYTHON教程 Must Know PYTHON Tutorials
- • python 解释器
- • python idle
- • python dir函数
- • python 数据类型
- • python type函数
- • python 字符串
- • python 整型数字
- • python 列表
- • python 元组
- • python 字典
- • python 集合
- • python 变量
- • python print
- • python 函数
- • python 类定义
- • python import
- • python help
- • python open
- • python 异常处理
- • python 注释
- • python continue
- • python pass
- • python return
- • python global
- • python assert
- • python if语句
- • python break
- • python for循环
- • python while循环
- • python else/elif
- • lambda匿名函数
必知PYTHON模块 Must Know PYTHON Modules
- • os 模块
- • sys 模块
- • re 正则表达式
- • time 日期时间
- • pickle 持久化
- • random 随机
- • csv 模块
- • logging 日志
- • socket网络通信
- • json模块
- • urlparse 解析URL
- • urllib 模块
- • urllib2 模块
- • robotparser 解析
- • Cookie 模块
- • smtplib 邮件
- • Base64 编码
- • xmlrpclib客户端
- • string 文本
- • Queue 线程安全
- • math数学计算
- • linecache缓存
- • threading多线程
- • sqlite3数据库
- • gzip压缩解压
最新内容 NEWS
- • django app提供pv信息的方法是什么
- • Django项目版本升级如何操作?
- • django较多数据传递如何优雅的呈现
- • django1.7获取参数问题求助
- • Django1.7使用内置comment遇到问题
- • python mysql数据库做insert操作时报_mysql_ex
- • 关于python mysql的duplicate insert机制的疑问
- • pymongo使用insert函数批量插入被中断要怎么
- • Python程序员解决棘手问题的常用库
- • 求助关于restfull api接口几个问题
图文精华 RECOMMEND
-
django1.7获取参数问题求助
-
Python程序员解决棘手问题的常用库
-
求问str()同__str__原理上有什么不同
-
scrapy框架里面用link extractor怎么能
-
python {}.fromkeys创建字典append添加操
-
python3 类型Type str doesn't support th
热点文章 HOT
- 学习Python有什么好的书籍推荐?
- Python匿名函数 Lambda表达式作用
- Python与Java、C、Ruby、PHP等编程语言有什么
- Python 正则中文网页字符串提取问题
- 如何为实时性应用存取经纬度?django my
- 想用python做个客户端,在二维码登录这个地
- 有让IDE可识别Python函数参数类型的方法吗
- Python字符串转换成列表正则疑问