用python twisted写服务器程序

本文介绍了一个使用Twisted框架实现的基本聊天服务器脚本。该服务器通过简单的状态机处理客户端连接及认证流程,并能接收和响应客户端输入。适用于快速搭建用于客户端软件测试的简易聊天服务器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天要测试客户端软件,身边没有服务器端,没办法,写了一个服务器的小脚本,用来测试客户端的正确性,发现比用Python的Socket模块
还是方便了许多
.#coding:gb2312
"""The most basic chat protocol possible.

run me with twistd -y chatserver.py, and then connect with multiple
telnet clients to port 1025
"""

from twisted.protocols import basic



class MyChat(basic.LineReceiver):
    def connectionMade(self):
        self.Stat='AUTHA'
        print "Got new client!"
        self.message("""
欢迎登录\r""")
        self.factory.clients.append(self)

    def connectionLost(self, reason):
        print "Lost a client!"
        self.factory.clients.remove(self)

    def lineReceived(self, line):
        s=repr(line)
        print "received+["+s+"]STAT:"+ self.Stat
        if self.Stat=='AUTHA':
            print '操作员:'
            self.message('\n\r操作员:')
            self.Stat='AUTH'
        elif self.Stat=='AUTH':
            print '请输入口令:'
            self.message('\n\r请输入口令:')
            self.Stat='PASS'
        elif self.Stat=='PASS':
            print 'MML>'
            self.message('\n\rMML>')
            self.Stat='DATA'
        elif self.Stat=='DATA':
            if s=="'quit'":
                print 'Good bye!'
                self.loseConnection()
            else:
                self.message('\n\r指令执行成功\n\rMML>')

    def message(self, message):
        self.transport.write(message)


from twisted.internet import protocol
from twisted.application import service, internet

factory = protocol.ServerFactory()
factory.protocol = MyChat
factory.clients = []

application = service.Application("chatserver")
internet.TCPServer(2026, factory).setServiceParent(application)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值