When I run the client / server together, and try to send a message, it doesn’t seem like either of them recieves anything. Why?
client.py:
import socket, sys
import threading
# Client for WutChat #
PORT = 5000
queue = []
def exitClient(s):
s.close()
print "Exiting..."
sys.exit()
def connect(host, port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try: s.connect((host, port))
except: return "error"
return s
def recieveData(s):
while True:
data = s.recv(512)
if not data: continue
if data in queue:
continue
queue.append(data)
print data
def sendData(s):
while True:
try: data = raw_input(">")
except EOFError: exitClient(s)
if data == "": print "no msg"; continue;
if data.startswith("/"):
print "Command detected"
continue
s.send(data)
if __name__ == "__main__":
s = connect(sys.argv[1], int(sys.argv[2]))
threading.Thread(target=recieveData, args=(s,)).start()
threading.Thread(target=sendData, args=(s,)).start()
server.py:
import socket, sys
import threading
# Server for WutChat #
PORT = 5000
DEBUG = True
conns = {}
msgqueue = []
def connect():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try: s.bind(("", int(sys.argv[1])))
except IndexError: s.bind(("", PORT))
s.listen(1)
while True:
addr, obj = s.accept()
conns[addr] = obj
print str(addr)+" connected!"
threading.Thread(target=handle, args=(addr, obj, s,)).start()
def handle(addr, obj, s):
while True:
try: msg = obj.recv(512)
except:
continue
print msg
msg = addr + msg
msgqueue.append(msg)
if DEBUG: print msgqueue
for conn in conns:
for message in msgqueue:
conns[conn].send(message)
del message
if __name__ == "__main__":
connect()
You have switched around the resulting tuple of accept:
should be
To find errors like these, remove the generic try..except block in
handle, and catch only the specific errors you want to. In your specific case (ifobj.recvfails), you can catchsocket.error, but the only sensible thing to do when that happens is to close the socket and terminate the thread.On an unrelated note, you may want to have a more descriptive name than
obj. How aboutclient_sockor simplysock?Also,
will fail because addr is a tuple, and msg a bytestring. You want
Additionally,
just removes the name
message, and is a no-op in your case. You probably want to useQueue.getinstead.