Python聊天客户端未保持打开状态
我最近开始开发一个用于学习的服务器-客户端聊天协议(稍后,我想对这种通信做更多的工作,但现在这已经足够了。不用说,我还处于Python这一部分的学习阶段,但我已经修改了一些示例,使之成为我在网上找到的服务器和客户端。从我目前所看到的情况来看,这种通信工作得很好,但我每次都必须重新启动客户端我想向服务器发送一条消息。 代码如下: 服务器:Python聊天客户端未保持打开状态,python,chat,Python,Chat,我最近开始开发一个用于学习的服务器-客户端聊天协议(稍后,我想对这种通信做更多的工作,但现在这已经足够了。不用说,我还处于Python这一部分的学习阶段,但我已经修改了一些示例,使之成为我在网上找到的服务器和客户端。从我目前所看到的情况来看,这种通信工作得很好,但我每次都必须重新启动客户端我想向服务器发送一条消息。 代码如下: 服务器: from twisted.internet import reactor, protocol from twisted.protocols import bas
from twisted.internet import reactor, protocol
from twisted.protocols import basic
class Echo(protocol.Protocol):
def dataReceived(self, data):
"As soon as any data is received, write it back."
self.transport.write(data)
class MyChat(basic.LineReceiver):
def connectionMade(self):
print "Got new client!"
self.factory.clients.append(self)
def connectionLost(self, reason):
print "Lost a client!"
self.factory.clients.remove(self)
def dataReceived(self, data):
print "received", repr(data)
for c in self.factory.clients:
c.message(data)
def message(self, message):
self.transport.write(message + '\n')
def main():
"""This runs the protocol on port 8000"""
factory = protocol.ServerFactory()
factory.protocol = MyChat
factory.clients = []
reactor.listenTCP(8000,factory)
reactor.run()
# this only runs if the module was *not* imported
if __name__ == '__main__':
main()
客户:
from twisted.internet import reactor, protocol
# a client protocol
class EchoClient(protocol.Protocol):
"""Once connected, send a message, then print the result."""
def connectionMade(self):
self.transport.write("hello, world!")
def dataReceived(self, data):
"As soon as any data is received, write it back."
print "Server said:", data
self.transport.loseConnection()
def connectionLost(self, reason):
print "connection lost"
class EchoFactory(protocol.ClientFactory):
protocol = EchoClient
def clientConnectionFailed(self, connector, reason):
connector.connect()
print "Connection failed - goodbye!"
reactor.stop()
def clientConnectionLost(self, connector, reason):
connector.connect()
print "Connection lost - goodbye!"
reactor.stop()
# this connects the protocol to a server runing on port 8000
def main():
f = EchoFactory()
client = EchoClient()
reactor.connectTCP("localhost", 8000, f)
reactor.run()
# this only runs if the module was *not* imported
if __name__ == '__main__':
main()
我忘了添加什么,以便我可以将多个客户端连接到服务器并保持连接?
我看了看(第一个问题似乎是同一类型的问题),但对于如何解决这个问题,我仍然感到困惑。任何建议都很感谢。谢谢!FYI您的链接没有正确通过。哎呀!谢谢!我会修复,断开连接应该是收到的数据的一部分吗?