1
我是新來的Python扭了,我決定創建這個作爲我的學習過程的一部分:Python的扭曲:更改目錄爲每個客戶端獨立
我創建使用Python扭曲的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()
好的,我會試試看。謝謝! – epark009