我有这段代码片段,用于与客户建立连接,然后将所有文本写入文件。这是代码
void Person::set_job_name(char * n)
{
obj.set_name(n);
}
我正在执行此命令from twisted.internet.protocol import Protocol, Factory
from twisted.internet import reactor
import ctypes # An included library with Python install.
class DataTransfer(Protocol):
def connectionMade(self):
#self.transport.write("""connected""")
fwrite = open('/Applications/mamp/htdocs/datatest.txt','r+')
self.factory.clients.append(self)
print "clients are ", self.factory.clients
self.username = ""
self.password = ""
self.auth = False
self.ipaddress = self.transport.getPeer()
print self.ipaddress
def connectionLost(self, reason):
fwrite.close()
self.factory.clients.remove(self)
print reason
def dataReceived(self, data):
print data
fwrite.write(data)
a = data.split(':')
if len(a) > 1:
command = a[0]
content = a[1]
msg = ""
self.message(msg)
def message(self, message):
self.transport.write(message + '\n')
factory = Factory()
factory.protocol = DataTransfer
factory.clients = []
reactor.listenTCP(8889, factory)
print "Server started"
reactor.run()
。服务器启动成功。但是当我使用netcat命令连接到它时,我在终端中得到以下内容,连接关闭。
pythonw socketListner.py
答案 0 :(得分:0)
您的变量fwrite
是在connectionMade
中本地定义的。尝试将其定义为实例变量,方法是在您的类中使用它时将其定义为self.fwrite
。