I have a client-server socket python script. I want to keep the state of each connection, such that I identify whether or not the client is its first connection. I unsuccessfully wrote the following code:
import socket,sys,SocketServer
from threading import Thread
class EchoRequestHandler(SocketServer.BaseRequestHandler):
def setup(self):
self.clients = {}
print self.client_address, 'connected!'
self.request.send('hi ' + str(self.client_address) + '\n')
def setup(self):
print self.client_address, 'connected!'
self.request.send('hi ' + str(self.client_address) + '\n')
def getFile(self):
fle = self.request.makefile('r')
filename = fle.readline()
print("Got filename {}\n".format(filename))
data = 'fnord' # just something to be there for the first comparison
with open(filename[:-1], 'w') as outfile:
while data:
#data = self.request.recv(1024)
data = fle.read()
#print('writing {!r} to file ....'.format(data))
outfile.write(data)
print("Finish {}\n".format(filename))
print("finish handle")
def handle(self):
addr = self.client_address[0]
print(self.clients)
if addr not in self.clients:
print("firsttime")
self.clients[addr]=1
print(self.clients)
self.getFile()
def finish(self):
print self.client_address, 'disconnected!'
#self.request.send('bye ' + str(self.client_address) + '\n')
class ThreadedTCPServer(SocketServer.ThreadingMixIn,
SocketServer.TCPServer):
pass
if __name__=='__main__':
#server = SocketServer.ThreadingTCPServer(('localhost', 50000), EchoRequestHandler)
server = ThreadedTCPServer(('localhost', 60000), EchoRequestHandler)
server.serve_forever()
Each time the client connect I am getting an empty clients dictionary. Seems like each time there is a connection setup is being called and empties the dictionary clients
. How can I keep its state at each connection?