如何打破一段时间的真实陈述

时间:2015-10-20 16:06:37

标签: python-2.7 network-programming

我是Pytnon Networking的初学者。我正在编写这个程序,其中服务器将打印客户端写入的任何内容。如果客户端终止连接,我不知道如何以最佳方式中断while语句。

from socket import *


host = gethostname()
port = 27000
svr = socket(AF_INET, SOCK_STREAM)
svr.bind((host, port))
svr.listen(1)

print "Waiting for client connection..."
print "..."

c, addr = svr.accept()
print 'Got connection from', addr

while True:
    print c.recv(1024)

3 个答案:

答案 0 :(得分:2)

我试过这个。有用。希望你明白这一点。

while True:
    n = raw_input("Some bla bla':")
    if n.strip() == 'hello':
        break

答案 1 :(得分:1)

考虑使用Twisted? Twisted有一些非常好的功能,可以让你这样做,例如我的服务器只是鹦鹉回到它听到的内容:

from twisted.internet import protocol, reactor
from twisted.protocols.basic import LineReceiver

class Echo(LineReceiver):
    def dataReceived(self, data):
        self.transport.write(data)

    def connectionLost(self, reason):
        print 'Client connection lost. Reason:\n{r}\n'.format(r=reason)
        LineReceiver.connectionLost(self, reason)
        reactor.stop()

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

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

套接字在很低的水平上很好但有时候太基本......

让你进入Twisted世界考虑阅读:http://krondo.com/blog/?page_id=1327

答案 2 :(得分:0)

我会尝试这样的事情

while True:
   userInput = #here you insert whatever your user entered
   if userInput == "Insert break statement here": #you could insert here something like "I want to get out of this function" or something like that, so that user wouldn't just accidentally type it
      break
   else:
      print(userInput)