如何在python中实现非阻塞套接字服务器

时间:2013-06-04 13:26:35

标签: python multithreading sockets blocking nonblocking

一个类似但不同的问题:

我有一个生成字符串的IRC客户端。每当有人说某事时,这个IRC客户端使用一个钩子来调用一个方法(somone_said)。我想通过套接字将此字符串发送到我的Flash客户端。

我在flash中有一个工作客户端,在python中有一个服务器,但问题是它阻塞: 1)在监听客户端连接时 2)在等待生成下一条消息时

这会阻止IRC客户端响应其他输入。

我认为我需要在一个单独的线程中创建我的套接字,但这会产生另外三个问题。 1)我的someone_said事件驱动方法如何访问套接字 2)如果有人在没有服务器客户端连接(正在收听)或客户端已关闭连接时说某事,该怎么办? 3)如何检查线程是否存活以及是否打开新线程?

我的阻止服务器代码是:

# Echo server program
import socket
import sys

HOST = None               # Symbolic name meaning all available interfaces
PORT = 7001              # Arbitrary non-privileged port
s = None

def startListening():
    print "starting to listen"

    for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC,
                                  socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
        af, socktype, proto, canonname, sa = res
        try:
            s = socket.socket(af, socktype, proto)
        except socket.error as msg:
            s = None
            continue
        try:
            s.bind(sa)
            s.listen(1)
        except socket.error as msg:
            s.close()
            s = None
            continue
        break
    if s is None:
        print 'could not open socket'
        sys.exit(1)
    conn, addr = s.accept()
    print 'Connected by', addr
    while 1:
        try: 
            data = conn.recv(1024)
        except:
            print "cannot recieve data"
            break
        if not data: 
            break
        print data
        message = ""
        while not "quit" in message:
            message = raw_input('Say Something : ') # This will come from event driven method
            try: 
                conn.sendall(message)
            except Exception as exc:
                print "message could not be sent"
                break


    conn.close()
    print "connection closed"

while 1:
    startListening()

xchat模块python脚本的工作原理如下(需要运行HexChat)

__module_name__ = "Forward Module"
__module_version__ = "1.0.0"
__module_description__ = "Forward To Flash Module by Xcom"

import sys
import xchat

def someone_said(word, word_eol, userdata):
    # method called whenever someone speaks in IRC channel
    username = str(word[0]) # From IRC contains the username string
    message = str(word[1]) # From IRC contains the user message
    sendString = username + " : " + message
    send_to_server(sendString)


def send_to_server(message):
    # send over socket method to be implemented here

xchat.hook_print('Channel Message' , someone_said)

我几天来一直在撞墙。帮助我obi wan kenobi,你是我唯一的希望。

1 个答案:

答案 0 :(得分:4)

看看Asyncore,它正是为你正在寻找的东西完成的:)

http://docs.python.org/2/library/asyncore.html

干杯,

ķ。