I'm writing a multi-threaded, multi-client server in python. Multiple users can connect to it with telnet and basically use it as a chat server. I'm able to connect with two clients through telnet, but I run into the two following problems:
- The first client to send a message is immediately disconnected.
- The other client does not the receive the message sent by the first client.
Server code:
import os
import sys
import socket
import thread
port = 1941
global message
global lock
global file
def handler(connection):
while 1:
file = connection.makefile()
file.flush()
temp = file.readline()
if temp == 'quit':
break
lock.acquire()
message += temp
lock.release()
file.write(message)
file.close()
acceptor = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
acceptor.bind(('', port))
acceptor.listen(10)
lock = thread.allocate_lock()
while 1:
connection, addr = acceptor.accept()
thread.start_new_thread(handler, (connection,))
Ok I listened to unholysampler and now I have this. I'm able to to connect with both clients now and type messages, but they aren't being sent/received (I can't tell which one).
import os
import sys
import socket
import thread
port = 1953
def handler(connection):
global message
global filelist
filelist = []
file = connection.makefile()
file.flush()
filelist.append(file)
message = ''
while 1:
i = 0
while i < (len(filelist)):
filelist[i].flush()
temp = filelist[i].readline()
if temp == 'quit':
break
with lock:
message += temp
i = i + 1
file.close()
global lock
acceptor = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
acceptor.bind(('', port))
acceptor.listen(10)
lock = thread.allocate_lock()
while 1:
connection, addr = acceptor.accept()
thread.start_new_thread(handler, (connection,))