AYE89

coding & learning

导航

python网络编程(一)

Posted on 2017-08-03 09:11  AYE89  阅读(229)  评论(0编辑  收藏  举报

一、Server

带“会话”类的服务器程序

asyncore    异步套接字处理程序

asynchat     asyncore的增强版,chat-style或者命令响应协议

 

from asyncore import dispatcher
from asynchat import async_chat
import socket, asyncore

PORT = 5005

class ChatSession(async_chat):

    def __init__(self, sock):
        async_chat. init (self, sock)
        self.set_terminator("\r\n")
        self.data = []

    def collect_incoming_data(self, data):
        self.data.append(data)

    def found_terminator(self):
        line = ''.join(self.data)
        self.data = []
        # Do something with the line...
        print(line)

class ChatServer(dispatcher):

    def __init__(self, port): dispatcher. init (self)
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.set_reuse_addr()
        self.bind(('', port))
        self.listen(5)
        self.sessions = []

    def handle_accept(self):
        conn, addr = self.accept()
        self.sessions.append(ChatSession(conn))

if __name__ == '__main__':
    s = ChatServer(PORT)
    try: asyncore.loop()
    except KeyboardInterrupt: print()

1.用到的类:

dispathcher类基本上是一个套接字类型;

async_chat类隐藏了大多数套接字读写操作;

2.作用

1)ChatServer的  

self.sessions = []

用来保存回话列表 ;

 

handle_accpet方法创建了新的ChatSession对象,并且将其追加到会话列表中;

2)conn, addr = self.accept()

conn是一个sock

3)asyncore.loop()

启动服务器,开始监听端口;

 

二、聊天服务器

class ChatServer(dispatcher):
    """
    A class that receives connections and spawns individual
    sessions. It also handles broadcasts to these sessions.
    """
    def __init__(self, port, name):
        # Standard setup tasks 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.sessions = []

    def disconnect(self, session):
        self.sessions.remove(session)

    def broadcast(self, line):
        for session in self.sessions:
            session.push(line + '\r\n')

    def handle_accept(self):
        conn, addr = self.accept()
        self.sessions.append(ChatSession(self, conn))   

if __name__ == '__main__':
    s = ChatServer(PORT, NAME)
    try: asyncore.loop()
    except KeyboardInterrupt: print()

作用:

1)disconnect(self, session)用来处理客户端断开连接;

2)push方法:

session对象是ChatSession(async_chat)类型的,写入数据使用push方法;

3)self.sessions.append(ChatSession(self, conn))

self, conn 分别对应ChatSession构造函数server, sock

4)

def broadcast(self, line):
for session in self.sessions:

“广播”即是遍历会话列表;