从扭曲的客户端向服务器发送多条消息

时间:2014-02-25 22:10:35

标签: python networking twisted

我正在尝试构建客户端向服务器发送消息的客户端/服务器系统。服务器只是打印出客户端发送的内容。

from twisted.internet import protocol, reactor

class Echo(protocol.Protocol):
    def dataReceived(self, data):
        print data
        self.transport.write(data)

class EchoFactory(protocol.Factory):
    def buildProtocol(self, addr):
        return Echo()

reactor.listenTCP(8000, EchoFactory())
reactor.run()

问题在于,当我尝试使用此代码从客户端发送多条消息时,客户端在第一次连接后发出错误并发送。

from twisted.internet import reactor, protocol
import time

class EchoClient(protocol.Protocol):
   def __init__(self, message):
       self.message = message

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

   def dataReceived(self, data):
       print "Server said:", data
       self.transport.loseConnection()

class EchoFactory(protocol.ClientFactory):
   def __init__(self, message):
       self.message = message

   def buildProtocol(self, addr):
       return EchoClient(self.message)

   def clientConnectionFailed(self, connector, reason):
       print "Connection failed."
       reactor.stop()

   def clientConnectionLost(self, connector, reason):
       print "Connection lost."
       reactor.stop()

def sendMessage(message):
    reactor.connectTCP("localhost", 8000, EchoFactory(message))
    reactor.run()

if __name__ == "__main__":
    while True:
        r = raw_input(">")
        if r == 'q' or len(r) == 0: break
        sendMessage(r)

可能有什么问题?这是错误消息。

>a
Server said: a
Connection lost.
>b
Traceback (most recent call last):
  File "echoclient.py", line 38, in <module>
    sendMessage(r)
  File "echoclient.py", line 32, in sendMessage
    reactor.run()
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/twisted/internet/base.py", line 1168, in run
    self.startRunning(installSignalHandlers=installSignalHandlers)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/twisted/internet/base.py", line 1148, in startRunning
    ReactorBase.startRunning(self)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/twisted/internet/base.py", line 680, in startRunning
    raise error.ReactorNotRestartable()
twisted.internet.error.ReactorNotRestartable

3 个答案:

答案 0 :(得分:1)

虽然这个问题已经过时并且有两个不相关的答案,但我想为那些渴望了解的人回答这个问题。问题是,在dataReceived方法的服务器代码中,您有self.transport.write(data)(它将收到的每条消息都发送给客户端),同时在客户端代码中,再次在dataReceived方法中,您拥有命令self.transport.loseConnection()(一旦消息进入,它就会失去与服务器的连接)。所以,如果你删除任何这些行,你应该没事。在当前设置中,从客户端发送的第一条消息将被发送回客户端,这将导致连接断开。

此外,您在每次尝试发送邮件时都在调用reactor.run()。 Reactor.run应该只在主函数中调用一次。

答案 1 :(得分:0)

反应堆无法重启。

答案 2 :(得分:-1)

出于我自己的目的,使用套接字向服务器发送消息可以正常工作。

import socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('localhost', 8000))
while True:
    a = raw_input("> ")
    if a == 'q' or len(a) == 0: 
        client_socket.close()
        break
    else:
        client_socket.send(a)