我正在用python編寫一個多線程,多客戶端服務器。多個用戶可以用telnet連接它,基本上用它作爲聊天服務器。我可以通過telnet連接兩個客戶端,但遇到以下兩個問題:python中的多線程多客戶端服務器
- 第一個發送消息的客戶端立即斷開連接。
- 另一個客戶端不接收第一個客戶端發送的消息。
Server代碼:
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,))
好,我聽了unholysampler,現在我有這個。我現在能夠與兩個客戶端連接並輸入消息,但是他們沒有被髮送/接收(我不知道哪一個)。
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,))