python - Basic Socket Chat Program Using Multithreading Raises Errors -
i making basic chat program using socket , multi threading. program connected , when message sent client raises error on server side when executed:
exception in thread thread-1: traceback (most recent call last): file "c:\python27\lib\threading.py", line 810, in __bootstrap_inner self.run() file "c:\python27\lib\threading.py", line 763, in run self.__target(*self.__args, **self.__kwargs) file "c:\users\jclarke14\desktop\server - 2.py", line 25, in check_for_data data = c.recv(1024) file "c:\python27\lib\socket.py", line 174, in _dummy raise error(ebadf, 'bad file descriptor') error: [errno 9] bad file descriptor i beginner , new multi-threading , socket. doing wrong?
here code client:
#check incoming data def check_for_data(): while true: data = s.recv(1024) print "other: " + data print #send data def send_data(): while true: message = raw_input("you: ") print s.sendall(message) #start threads t = threading.thread(target=send_data) t.daemon = true t.start() #1 t = threading.thread(target=check_for_data) t.daemon = true t.start() #2 and code server:
c, addr = s.accept() print "connection from: " + str(addr) print def check_for_data(): while true: data = c.recv(1024) print "other: " + str(data) print def send_data(): while true: message = raw_input("you: ") print c.sendall(message) #start threads t = threading.thread(target=send_data) t.daemon = true t.start() #1 t = threading.thread(target=check_for_data) t.daemon = true t.start() #2 the full code available here: https://drive.google.com/folderview?id=0b3t3muqs3k-ilwy3y3jzx2yzu2c&usp=sharing
thank :)
after starting thread code closes remote socket in both server , client code. need wait thread complete before closing it's socket.
so, server remove last line c.close(). can wait in main thread child thread using t.join(). after can close socket.
you change thread code terminates when remote client closes socket. , better pass socket thread have thread access global variable:
def check_for_data(c): while true: data = c.recv(1024) if data: print "other: " + str(data) else: print "client closed connection" c.close() break t = threading.thread(target=check_for_data, args=(c,)) t.daemon = true t.start() t.join() #c.close() # if don't close in thread s.close() # close main server socket
Comments
Post a Comment