今天要测试客户端软件,身边没有服务器端,没办法,写了一个服务器的小脚本,用来测试客户端的正确性,发现比用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)
还是方便了许多
.#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)
本文介绍了一个使用Twisted框架实现的基本聊天服务器脚本。该服务器通过简单的状态机处理客户端连接及认证流程,并能接收和响应客户端输入。适用于快速搭建用于客户端软件测试的简易聊天服务器。
557

被折叠的 条评论
为什么被折叠?



