2013-06-25 10 views
1

내가 파이썬 트위스트에 새로 온 사람에 대한 디렉토리를 변경하고, 나는 나의 학습 과정의 일부로서이를 만들하기로 결정파이썬 트위스트 : 각 클라이언트 독립적

내가 파이썬 트위스트를 사용하여 TCP 클라이언트와 서버를 만들었습니다. 클라이언트는 서버에 명령을 보내서 디렉토리를 나열하고 디렉토리를 변경하며 파일을 볼 수 있습니다. 이 모든 것은 내가 원하는 방식대로 작동하지만 여러 클라이언트를 서버에 연결하고 그 중 하나에서 디렉토리를 변경하면 다른 클라이언트의 디렉토리도 변경됩니다! 이들을 독립적으로 만들 수있는 방법이 있습니까?

서버 코드

from twisted.internet.protocol import Protocol, Factory 
from twisted.internet import reactor 

import os 

class BrowserServer(Protocol): 
    def __init__(self): 
     pass 

    def dataReceived(self, data): 
     command = data.split() 

     message = "" 

     if command[0] == "c": 
      try: 
       if os.path.isdir(command[1]): 
        os.chdir(command[1]) 
        message = "Okay" 
       else: 
        message = "Bad path" 
      except IndexError: 
       message = "Usage: c <path>" 
     elif command[0] == "l": 
      for i in os.listdir("."): 
       message += "\n" + i 
     elif command[0] == "g": 
      try: 
       if os.path.isfile(command[1]): 
        f = open(command[1]) 
        message = f.read() 
      except IndexError: 
       message = "Usage: g <file>" 
      except IOError: 
       message = "File doesn't exist" 
     else: 
      message = "Bad command" 

     self.transport.write(message) 

class BrowserFactory(Factory): 
    def __init__(self): 
     pass 

    def buildProtocol(self, addr): 
     return BrowserServer() 

if __name__ == "__main__": 
    reactor.listenTCP(8123, BrowserFactory()) 
    reactor.run() 

클라이언트 코드

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

class BrowserClient(LineReceiver): 
    def __init__(self): 
     pass 

    def connectionMade(self): 
     print "connected" 
     self.userInput() 

    def dataReceived(self, line): 
     print line 
     self.userInput() 

    def userInput(self): 
     command = raw_input(">") 
     if command == "q": 
      print "Bye" 
      self.transport.loseConnection() 
     else: 
      self.sendLine(command) 

class BrowserFactory(ClientFactory): 
    protocol = BrowserClient 

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

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

if __name__ == "__main__": 
    reactor.connectTCP("localhost", 8123, BrowserFactory()) 
    reactor.run() 

답변

1

당신이 할 수없는, 심지어 (IIRC) 프로세스의 모든 스레드에 영향을 미치는 디렉토리 참조를 유지하고 전체와 listdiropen를 호출 스레드 chdir를 사용하여 경로

+0

좋아, 내가 해보겠습니다. 감사! – epark009

관련 문제