Twisted 实现的客户端和服务器端的单次连接问题
1服务器端代码:
from twisted.internet.protocol import Factory
from twisted.protocols.basic import LineReceiver
from twisted.internet import reactor
import pdb
class Chat(LineReceiver):
def __init__(self, users):
self.users = users
self.name = None
self.state = "GETNAME"
def connectionMade(self):
self.sendLine("Please input your url:")
def connectionLost(self, reason):
if self.name in self.users:
del self.users[self.name]
def lineReceived(self, line):
#pdb.set_trace()
if self.state == "GETNAME":
self.handle_GETNAME(line)
def handle_GETNAME(self, name):
if name in self.users:
#self.sendLine("Name taken, please choose another.")
pass
#pdb.set_trace()
print name
self.sendLine("%s"%(name))
self.name = name
self.users[name] = self
self.state = "GETNAME"
#pass
class ChatFactory(Factory):
def __init__(self):
self.users = {} # maps user names to Chat instances
def buildProtocol(self, addr):
return Chat(self.users)
reactor.listenTCP(8080, ChatFactory())
reactor.run()
2.客户端代码:
from twisted.internet import protocol,reactor
from twisted.protocols.basic import LineReceiver
HOST='localhost'
PORT=8080
class TSClntProtocol(LineReceiver):
def connectionMade(self):
#self.sendLine("reader")
pass
def lineReceived(self,line):
print "%s"%line
#message=raw_input(">")
message="http://localhost:8080"
self.sendLine(message)
self.transport.loseConnection()
class TSClntFactory(protocol.ClientFactory):
protocol=TSClntProtocol
#clientConnectionLost=clientConnectionFailed=\
#lambda self,connector,reason:reactor.stop()
reactor.connectTCP(HOST,PORT,TSClntFactory())
reactor.run()
浙公网安备 33010602011771号