Modify server's variable from client's thread (threading, python)
multithreading, python
Solution
Generate the random number that is shared between both server and all the client, there should be only instance of this, hence this should be class attribute. Add a class function `guess` which return `False` upon incorrect guess and upon correct guess changes the `randnum` and returns `True`
class Server:
randnum = randint(1, 1000) # class attribute created
@classmethod
def guess(cls, no): # To be used "guess" if `no` attribute if the same as `cls.randnum`
if cls.randnum == no:
cls.randnum = randint(1, 1000)
result = True
else:
result = False
return result
def __init__(self, ip, port):
# ...
The client should call this `Server.guess` function each time.
Problem
I implemented a simple network 'game' in Python - server draws a random number, and then the client tries to guess it. My application works great, when the client guesses the number, it disconnects from server (it is handled on client's side). However, after the proper guess, the number is still the same. I would like to modify the application, such that when the client guesses the number, the server should then rand a new number, so other clients should guess the new one. How can I do this? Some template, just to draw an attention to the problem: ``` #!/usr/bin/env python from random import randint import socket, select from time import gmtime, strftime import threading import sys class Handler(threading.Thread): def __init__(self, connection, randomnumber): threading.Thread.__init__(self) self.connection = connection self.randomnumber = randomnumber def run(self): while True: try: data = self.connection.recv(1024) if data: print data try: num = int(data) if Server.guess(num) : msg = "You won! This is the right number!" self.connection.send(msg) break else : msg = "Try again!" self.connection.send(msg) except ValueError, e: msg = "%s" % e self.connection.send(msg) else: msg = "error" self.connection.send(msg) except socket.error: self.connection.close() break self.connection.close() class Server: def __init__(self, ip, port): self.ip = ip self.port = port self.address = (self.ip, self.port) self.server_socket = None self.randnum = randint(1, 100) @classmethod def guess(cls, no): if cls.randnum == no: cls.randnum = randint(1, 1000) result = True else: result = False return reslut def run(self): try: self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server_socket.bind((self.ip, self.port)) self.server_socket.listen(10) print 'Num is %s' % self.randnum while True: connection, (ip, port) = self.server_socket.accept() c = Handler(connection, self.randnum) c.start() except socket.error, e: if self.server_socket: self.server_socket.close() sys.exit(1) if __name__ == '__main__': s = Server('127.0.0.1', 1234) s.run() ```