Python Twisted:独立更改每个客户端的目录

时间:2013-06-25 22:40:17

标签: python client-server twisted

我是Python Twisted的新手,我决定将其作为学习过程的一部分来创建:

我使用Python Twisted创建了一个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 个答案:

答案 0 :(得分:1)

你不能,即使使用线程chdir也会影响进程中的所有线程(iirc),保留目录引用并以完整路径调用listdiropen