Python套接字:简单客户端连接脚本的错误文件描述符

时间:2015-09-20 10:54:41

标签: python sockets proxy server

我的脚本非常简单。

1。)服务器侦听HTTP连接

2.。)客户建立连接

3.)服务器打印客户端的HTTP请求数据

当客户端连接到服务器并发出浏览器请求时,它会触发Socket错误" Bad File Descriptor"。

我不确定为什么会这样做。任何人都可以帮助我吗?

import socket

host = ''
port = 1000


def proxy(connection,client):
    request = connection.recv(MAX_DATA_RECV)
    print request
    connection.close()

def main():
    try:
            # create a socket
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            # associate the socket to host and port
            s.bind((host, port))
            # listenning
            s.listen(BACKLOG)
            print("Listening for connections")

    except socket.error, (value, message):
            if s:
                    s.close()
                    print "Could not open socket:", message
                    # get the connection from client
    while 1:
            try:
                    conn, client_addr = s.accept()
                    print("Received connection from " + str(client_addr))
                    proxy(conn,client_addr)
                    #thread.start_new_thread(proxy, (conn,client_addr))
                    if s:
                            s.close()
            except socket.error, (value,message):
                    print value
                    print message
                    sys.exit(1)


main()

1 个答案:

答案 0 :(得分:1)

您正在关闭第一个客户端后的服务器套接字。不要这样做。

while True:
    try:
        conn, client_addr = s.accept()
        print("Received connection from " + str(client_addr))
        proxy(conn,client_addr)
    except socket.error, (value,message):
        print value
        print message