I've just posted a part of my program. The first time I run the program I could give the input from a client and the server crosses the accept, but when the program runs for second loop it gets stuck in the mysocket.accept
. Making the socket non-blocking doesn't solve this.Does anyone know how to clear this error?
class Memory(threading.Thread):
def __init__ (self):
threading.Thread.__init__ (self)
def run(self):
global data_queue
while True:
sleep(0.1)
mysock.listen(5)
print "waiting for data"
conn, addr = mysock.accept()
print "received data from client"
data = conn.recv(1000)
data_queue.put(data)
class Execute(threading.Thread):
def __init__ (self):
threading.Thread.__init__ (self)
def run(self):
global data_queue
while True:
if not data_queue.empty():
data = data_queue.get()
if not data:
break
if data == b'on':
print "on"
gpio.output(4,True)
if data == b'off':
print "off"
gpio.output(4,False)
Client Program:
try:
a = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
print("Failed to create socket")
sys.exit()
a.connect(('127.0.0.1', 1236))
while True:
print "1.ON 2.OFF"
choice = input('Enter your choice')
if choice == 1:
try:
a.sendall(b"on")
except socket.error:
print("Failed to send")
sys.exit()
if choice == 2:
try:
a.sendall(b"off")
except socket.error:
print("Failed to send")
sys.exit()
ms.close()
I believe what you want in your Memory thread is this:
def __init__ (self):
threading.Thread.__init__ (self)
def run(self):
global data_queue
mysock.listen(5)
print "waiting for data"
while True:
sleep(0.1)
conn, addr = mysock.accept()
print "received connection from client"
self.talk_to_client(conn)
def talk_to_client(self, conn):
data = conn.recv(1000)
while data != 'quit':
reply = prepare_reply_to_client(data)
data_queue.put(reply)
conn.close() # if we're done with this connection
Notice how I've moved the listen up above the while loop so it only happens once. Your problem is that your second call to listen() conflicts with the first. You should only call listen once. Subsequent accepts will clone the listen socket and use it for a connection. You then close that connection when your done with it, but your listen continues waiting for new connections.
Here's the canonical example in the python docs: https://docs.python.org/2/library/socket.html#example
Updated: Add example of extended interaction with client by writing method talk_to_client(conn)