【发布时间】:2011-07-29 11:27:54
【问题描述】:
我正在用 python 编写一个多线程、多客户端服务器。多个用户可以通过 telnet 连接到它,基本上将其用作聊天服务器。我可以通过 telnet 与两个客户端连接,但我遇到了以下两个问题:
- 第一个发送消息的客户端立即断开连接。
- 另一个客户端没有收到第一个客户端发送的消息。
服务器代码:
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,))
【问题讨论】:
标签: python multithreading sockets echo