1

我是 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()
4

1 回答 1

1

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

于 2013-06-25T22:44:50.140 回答