Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么我在这里遇到连接重置错误?_Python_Select_Python 3.x_Python Asyncio - Fatal编程技术网

Python 为什么我在这里遇到连接重置错误?

Python 为什么我在这里遇到连接重置错误?,python,select,python-3.x,python-asyncio,Python,Select,Python 3.x,Python Asyncio,我是Python3的新手,正在使用asyncio。因此,我在以下服务器端代码中遇到了一个奇怪的行为: import asyncio @asyncio.coroutine def handle_client(reader, writer): print('Client connected.') client_connected = True while client_connected: print('Waiting for client event.'

我是Python3的新手,正在使用asyncio。因此,我在以下服务器端代码中遇到了一个奇怪的行为:

import asyncio


@asyncio.coroutine
def handle_client(reader, writer):
    print('Client connected.')
    client_connected = True
    while client_connected:
        print('Waiting for client event.')
        line = yield from reader.readline()
        if line:
            print('Got: {}'.format(line))
            if line.decode() == 'echo\n':
                print('Sending back echo.')
                writer.write(line)
            else:
                print('Not sending back anything.')
        else:
            print('Client disconnected.')
            client_connected = False


if __name__ == '__main__':
    asyncio.async(asyncio.start_server(handle_client, 'localhost', 8888))
    asyncio.get_event_loop().run_forever()
当我运行此客户机代码时(编辑:客户机代码是手动输入到IPython会话中的,在我关闭套接字之前,服务器肯定有时间进行写入)

。。。我从服务器得到一个错误回溯:

C:\Users\Gnar\Anaconda3\python.exe C:/Users/Gnar/Code/echo.py
Client connected.
Waiting for client event.
Got: b'echo\n'
Sending back echo.
Waiting for client event.
Task exception was never retrieved
future: <Task finished coro=<handle_client() done, defined at C:/Users/Gnar/Code/echo.py:4> exception=ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None)>
Traceback (most recent call last):
  File "C:\Users\Gnar\Anaconda3\lib\asyncio\tasks.py", line 234, in _step
    result = coro.throw(exc)
  File "C:/Users/Gnar/Code/echo.py", line 10, in handle_client
    line = yield from reader.readline()
  File "C:\Users\Gnar\Anaconda3\lib\asyncio\streams.py", line 425, in readline
    yield from self._wait_for_data('readline')
  File "C:\Users\Gnar\Anaconda3\lib\asyncio\streams.py", line 393, in _wait_for_data
    yield from self._waiter
  File "C:\Users\Gnar\Anaconda3\lib\asyncio\futures.py", line 386, in __iter__
    yield self  # This tells Task to wait for completion.
  File "C:\Users\Gnar\Anaconda3\lib\asyncio\tasks.py", line 287, in _wakeup
    value = future.result()
  File "C:\Users\Gnar\Anaconda3\lib\asyncio\futures.py", line 275, in result
    raise self._exception
  File "C:\Users\Gnar\Anaconda3\lib\asyncio\selector_events.py", line 662, in _read_ready
    data = self._sock.recv(self.max_size)
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host
相应的服务器日志:

C:\Users\Gnar\Anaconda3\python.exe C:/Users/Gnar/Code/echo.py
Client connected.
Waiting for client event.
Got: b'foo\n'
Not sending back anything.
Waiting for client event.
Client disconnected.
我错过了什么?我是否错误地使用了asyncio


谢谢

出现异常是因为您试图在服务器端将一些数据写回客户端,但客户端在发送
'echo'
后立即关闭
套接字,而实际上没有收到服务器的响应。如果套接字连接在线路上有未接收的数据时关闭,则发送端将出现错误,这样您就知道远程端可能没有收到您上次发送的数据


如果在调用
socket.close()
之前,在客户端添加对
socket.recv(1024)
的调用,以便客户端在关闭套接字之前等待服务器的响应,那么问题就会消失。如果您只是想优雅地处理异常,即使客户端做了错误的事情,您也可以在服务器端的写调用周围使用
try
/
,但
除外。

我怀疑这种情况是否属实。我的客户示例可能有点误导。事实上,所有客户端代码都是手动输入到IPython会话中的(我将把它编辑到问题中)。因此,在关闭客户端之前,服务器应该有足够的时间进行写入。此外,如果仔细查看回溯,服务器错误会出现在“readline”上。@gnargnagnar尝试一下;如果您
recv
服务器写入的数据,错误就会消失。如果写入套接字的数据在连接关闭时未被对等方实际接收到,则会发生错误-因此,即使
写入操作已完成,如果对等方在未读取该数据的情况下关闭连接,本地端在其关闭时运行的任何套接字操作都会出错。不过,我确实同意,我最初的回答并没有明确说明这一点。我会编辑它。是的,你是对的。如果在关闭之前与客户机一起接收回显,则不会出现服务器错误。服务器是否关心客户端是否读取了所有数据?也许我对插座有错误的看法。。
import socket
client = socket.create_connection(('localhost', 8888))
client.sendall('foo\n'.encode())
client.close()
C:\Users\Gnar\Anaconda3\python.exe C:/Users/Gnar/Code/echo.py
Client connected.
Waiting for client event.
Got: b'foo\n'
Not sending back anything.
Waiting for client event.
Client disconnected.