Unfortunately I am unable to find an answer for this even after an hour of searching.
I borrowed this from online tutorials - Youtube - Draps
import socket, threading, time, wx
tLock = threading.Lock()
shutdown = False
def receiving(name, sock):
while not shutdown:
try:
tLock.acquire()
#while True:
data, addr = sock.recvfrom(1024)
print str(data) + "hehehe"
except:
pass
finally:
tLock.release()
host = '127.0.0.1'
port = 0
server = ('127.0.0.1', 5000)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host,port))
s.setblocking(0)
rT = threading.Thread(target = receiving, args = ("RecvThread", s))
rT.start()
alias = raw_input("Name: ")
message = raw_input(alias + "-->")
while message != 'q':
if message != '':
s.sendto(alias + ":" + message, server)
tLock.acquire()
message = raw_input(alias + "-->")
tLock.release()
time.sleep(0.2)
shutdown = True
rT.join()
s.close()
I have two questions:
In the code,
host = '127.0.0.1'. However if I usesocket.gethostbyname(socket.gethostname()), I get a socket error. Could anyone tell me why is this so? When I deploy a similar code to an external computer, it should not have this problem of creating a socket.I started a thread that runs continuously. Why is the shutdown value (which is declared after the thread has started) able to stop the rT thread and break the while loop? I am unable to understand the physics and surprised it is working.