python中的多线程多客户端服务器

问题描述:

我正在用python编写多线程,多客户端服务器.多个用户可以使用telnet连接到它,并且基本上将其用作聊天服务器.我可以通过telnet与两个客户端连接,但是遇到了以下两个问题:

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:

  1. 第一个发送消息的客户端立即断开连接.
  2. 另一个客户端没有收到第一个客户端发送的消息.

服务器代码:

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,现在我有了这个.我现在可以同时与两个客户端连接并键入消息,但是没有发送/接收消息(我无法确定是哪个).

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,))

使用扭曲,它使您可以在单个线程中同时处理多个客户端,并提供更好的API.

It's much simpler and better to implement this sort of thing using Twisted, which lets you handle multiple clients concurrently in a single thread, as well as providing a nicer API.

以下是您使用Twisted编写聊天服务器的方式( chatserver.py ):

Here's how you write a chat server using Twisted (full example in chatserver.py):

class MyChat(basic.LineReceiver):
    def connectionMade(self):
        print "Got new client!"
        self.factory.clients.append(self)

    def connectionLost(self, reason):
        print "Lost a client!"
        self.factory.clients.remove(self)

    def lineReceived(self, line):
        print "received", repr(line)
        for c in self.factory.clients:
            c.message(line)

    def message(self, message):
        self.transport.write(message + '\n')

对于每个用户,都会创建一个MyChat对象,并且事件循环会在开始/停止事件以及从客户端接收到一行时调用其方法.在这种情况下,它只将接收到的每一行发送给系统中的所有客户端.由于它在单个线程中运行,因此不需要锁.

For each user, a MyChat object gets created, and the event loop calls its methods for start/stop events and when a line is received from the client. In this case, it just send every line it receives to all the clients in the system. Since it runs in a single thread, no locks are needed.