【问题标题】:ValueError on TCP communication PythonTCP通信Python上的ValueError
【发布时间】:2016-01-20 13:32:34
【问题描述】:

您好,我正在尝试通过 TCP 发送加密文件。 当运行服务器并发送一些文件时一切正常,但是当我再次尝试发送时,我在服务器端收到此错误:

Traceback (most recent call last):
File "server.py", line 38, in <module>
    f.write(l)
ValueError: I/O operation on closed file

我是 TCP 通信的新手,所以我不确定为什么文件关闭。

服务器代码:

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                 # Reserve a port for your service.
s.bind((host, port))        # Bind to the port

f = open('file.enc','wb')
s.listen(5)                 # Now wait for client connection.
while True:
    c, addr = s.accept()     # Establish connection with client.
    print 'Got connection from', addr
    print "Receiving..."
    l = c.recv(1024)
    while (l):
        print "Receiving..."
        f.write(l)
        l = c.recv(1024)
    f.close()
    print "Done Receiving"
    decrypt_file('file.enc', key)
    os.unlink('file.enc')
    c.send('Thank you for connecting')
    c.close()                # Close the connection

客户端代码:

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                 # Reserve a port for your service.
print '[1] send image'
choice = input('choice: ')

if choice == 1:
    encrypt_file('tosendpng.png', key)
    #decrypt_file('to_enc.txt.enc', key)

    s.connect((host, port))
    f = open('tosendpng.png.enc','rb')
    print 'Sending...'
    l = f.read(1024)
    while (l):
        print 'Sending...'
        s.send(l)
        l = f.read(1024)
    f.close()
    print "Done Sending"
    os.unlink('tosendpng.png.enc')
    s.shutdown(socket.SHUT_WR)
    print s.recv(1024)
    s.close()                     # Close the socket when done

【问题讨论】:

    标签: python sockets tcp communication


    【解决方案1】:

    据我所知,您的问题实际上与套接字无关。

    您在while 循环之前打开文件f,但在循环内部关闭它。因此,您第二次尝试写信给f 时,它已关闭。这也正是错误告诉您的内容。

    尝试将f = open('file.enc','wb') 移动到while 循环以解决此问题。

    【讨论】:

      【解决方案2】:

      问题与TCP完全无关,你的代码是

      f = open('file.enc','wb')
      while True:
          ...    
          f.write(l)
          ...
          f.close()
          ...
      

      第一个连接可以正常工作,但在此期间文件会关闭。将 f = open('file.enc','wb') 移动到 while True 循环内,以便在每次请求时重新打开文件。

      【讨论】:

        猜你喜欢
        • 2019-03-30
        • 2010-09-27
        • 2020-07-06
        • 1970-01-01
        • 2020-05-16
        • 1970-01-01
        • 1970-01-01
        • 2021-12-18
        • 1970-01-01
        相关资源
        最近更新 更多