从服务器发送时文件描述符错误 - python

时间:2014-03-17 06:53:15

标签: python networking text python-3.x

嗨,我无法弄清楚这个错误发生的原因。我已经发布了打印声明,并做了一个测试脚本来尝试找出问题所在,我无法弄清楚它为什么不起作用。

s = None
for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC,
                          socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
    af, socktype, proto, canonname, sa = res
    print ('Listening on', sa)
    try:
        s = socket.socket(af, socktype, proto)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    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)

def handler(signum, frame):
    s.close()
    sys.exit(1)

signal.signal(signal.SIGINT, handler)

while True:
    print('Waiting for connection...')
    conn, addr = s.accept()
    print ('Connection from', addr)
    while True:
        data = conn.recv(1024)
        if not data: 
            break
        print ('data: ' + data.decode('utf-8'))
        filetoOpen = data.decode('utf-8')
        print('filetoOpen: ' + filetoOpen)

        with open (filetoOpen, 'r') as myfile:
            contents=myfile.read().replace('\n', '')

        print('about to send :\n' + contents)
        conn.send(contents.encode('utf-8'))

        myfile.close()
        conn.close()

s.close()
sys.exit()

当我运行它时,我得到了

Traceback (most recent call last):
  File "server.py", line 67, in <module>
    data = conn.recv(1024)
OSError: [Errno 9] Bad file descriptor

我已经尝试过乱搞它,首先将信息保存到变量,谷歌搜索并在网上查看,我做了一个刚才有的测试脚本和

with open ('/u/students/dzhelabori/NWEN241/sample2.txt', 'r') as myfile:
    contents=myfile.read().replace('\n', '')

print(contents)
myfile.close()

工作正常并打印文件! 因此,当我尝试通过网络发送文本时会发生错误...但为什么它会说错误的文件描述符,我该怎么办?

1 个答案:

答案 0 :(得分:1)

您正在关闭连接:

while True:
    data = conn.recv(1024)
    # ...
    conn.close()

在此循环的第一次迭代之后,连接将关闭。然后在下一次迭代中,您尝试从已关闭的连接中recv

如果此时您已完成连接,那么为什么它处于while True循环中?