Reputation: 3198
I have this chat server code and the message passing basically doesn't work, im testing it with telnet, and its not sending anything I send it back out to the clients. I know that the clients are connected, infact the whole wait_for_connection() is working fine. I have a feeling its to do with my bad knowledge of multithreading in python. Could someone correct me ?
import socket, thread, sys
connections = []
isRunning = True
def wait_for_connection():
while isRunning:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(("", 1234))
s.listen(5);
print "Server is listening"
con, addr = s.accept()
print "Connected to", addr
connections.append(con)
def loop_through_connections():
for con in connections:
con.setblocking(0)
while isRunning:
for con in connections:
data = con.recv(100)
if not data:
break
for connection in connections:
connection.send(data)
if __name__ == "__main__":
thread.start_new_thread(wait_for_connection, ())
thread.start_new_thread(loop_through_connections, ())
while isRunning:
pass
Upvotes: 1
Views: 764
Reputation: 1315
I do not quite understand your code. I would suggest using fewer threads. Add a main loop in the main thread that accepts connections and for each connection that it accepts start a thread at a connection handler function. The function first sets blocking to false and then, in a loop, checks for data sent from the client and also sends out all data.
If a message was received from the client the function would append it to a master list of messages stored in one or more global variables. These variables would have to be set as global in each thread and function for it to work Please rate up this comment and feel free to reply with any questions
Upvotes: 2