Chinaunix首页 | 论坛 | 博客
  • 博客访问: 45491
  • 博文数量: 14
  • 博客积分: 10
  • 博客等级: 民兵
  • 技术积分: 132
  • 用 户 组: 普通用户
  • 注册时间: 2012-05-07 08:56
个人简介

此博客以后永不更新阴险阴险阴险阴险阴险阴险 国内唯一更新博客在此处不在更新,谢谢,请看下面的地址和邮箱! 我的博客园:http://www.cnblogs.com/mhxy13867806343/ 欢迎访问! 邮箱:mhxy13867806343@sina.cn/ 国内更新博客在:https://github.com/mhxy13867806343 微信公众号:pyjs

文章分类

全部博文(14)

文章存档

2017年(1)

2016年(4)

2015年(8)

2014年(1)

我的朋友

分类: Python/Ruby

2015-09-16 16:06:15

# -*- coding: utf-8 -*-
__author__ = 'Administrator'

#链接地址:     def do_logout(self,s,l):
        name=l.strip()
        if not name:
            s.push('please enter a name\r\n')
        elif name in self.server.users:
            s.push('the name "%s" is taken.\r\n'%name)
            s.push('please try again.\r\n')
        else:
            s.name=name
            s.enter(self.server.main_room)

class ChatRoom(Room):
    def add(self,session):
        self.broadcast(session.name+'has entered the room\r\n')
        self.server.users[session.name]=session
        Room.add(self,session)
    def remove(self,s):
        Room.remove(self,s)
        self.broadcast(s.name+'has left the room\r\n')
    def do_say(self,s,l):
        self.broadcast(s.name+':'+l+'\r\n')
    def do_look(self,s,l):
        s.push('the following are in this room:\r\n')
        for o in self.sessions:
            s.push(o+'\r\n')

class LogoutRoom(Room):
    def add(self,session):
        try:
            del self.server.users[session.name]
        except KeyError:pass

class ChatSession(async_chat):
    def __init__(self,server,sock):
        async_chat.__init__(self.sock)
        self.server=server
        self.set_terminator('\r\n')
        self.data=[]
        self.name=None
        self.enter(LoginRoom(server))
    def enter(self,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):
    def __init__(self,port,name):
        self.create_socket(socket.AF_INET,socket.SOCK_STREAM)
        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__':
    s=ChatServer(PORT,NAME)
    try:
        asyncore.loop()
    except KeyboardInterrupt:
        print


阅读(1094) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~