gpt4 book ai didi

Python 扭曲 : Changing directories for each client independently

转载 作者:太空宇宙 更新时间:2023-11-03 18:55:44 25 4
gpt4 key购买 nike

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

最佳答案

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

关于Python 扭曲 : Changing directories for each client independently,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17308784/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com