Reputation: 125
I am trying to make it so that, during any point in my client-server program, if the client wishes to exit the program, it sends data which the server will be able to receive no matter what the timing is.
To do this I have tried to use threading to run a thread in the background that listens for data "quit" in the background Whilst in the non threaded part of my code, it simply takes data as normal
Here is my attempt which (of course) did not work
Client:
import socket
host = str(socket.gethostbyname(socket.gethostname())) # Gets local IP so I don't have to keep changing
# host = "192.168.0.17"
port = 1000
ID = "__UserLogin123__"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
while True:
x = input("Send QUIT? -> ").upper()
if x == "Y":
s.send(str.encode("QUIT"))
else:
s.send(str.encode("foo"))
Server:
import socket
import queue
from threading import Thread
def foo(conn):
while True:
x = conn.recv(2048).decode()
if x == "QUIT":
return True
if x == "foo":
print("hollo")
result = False
port = 1000
host = str(socket.gethostbyname(socket.gethostname()))
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, port))
s.listen(1)
conn, addr = s.accept()
que = queue.Queue()
connThread = Thread(target=lambda q, arg1: q.put(foo(arg1)), args=(que,conn))
connThread.start()
while not result:
print("Waiting")
test = conn.recv(2048).decode()
if test == "foo":
print("hi")
result = que.get()
Upvotes: 1
Views: 86
Reputation: 724
This is not usually solved by multiple threads but rather by more layers. You simply create an additional layer, which will check only for quit word. If the processing word is not quit, then pass the word to the upper layers (your application logic). If yes, then don't pass anything up and simply quit the program.
Upvotes: 1