title: Websocket getting closed immediately after connecting to FastAPI Endpoint
body: <p>I'm trying to connect a websocket aiohttp client to a fastapi websocket endpoint, but I can't send or recieve any data because it seems that the websocket gets closed immediately after connecting to the endpoint.</p>
  <hr />
  <p><strong>server</strong></p>
  <pre class="lang-py prettyprint-override"><code>import uvicorn
  from fastapi import FastAPI, WebSocket
  
  app = FastAPI()
  
  @app.websocket('/ws')
  async def websocket_endpoint(websocket: WebSocket):
      await websocket.accept()
      ...
  
  
  if __name__ == '__main__':
      uvicorn.run('test:app', debug=True, reload=True)
  
  </code></pre>
  <p><strong>client</strong></p>
  <pre class="lang-py prettyprint-override"><code>import aiohttp
  import asyncio
  
  async def main():
      s = aiohttp.ClientSession()
      ws = await s.ws_connect('ws://localhost:8000/ws')
      while True:
          ...
  
  asyncio.run(main())
  </code></pre>
  <hr />
  <p>When I try to send data from the server to the client when a connection is made</p>
  <p><strong>server</strong></p>
  <pre class="lang-py prettyprint-override"><code>@app.websocket('/ws')
  async def websocket_endpoint(websocket: WebSocket):
      await websocket.accept()
      await websocket.send_text('yo')
  </code></pre>
  <p><strong>client</strong></p>
  <pre class="lang-py prettyprint-override"><code>while True:
     print(await ws.receive())
  
  </code></pre>
  <p>I always get printed in my client's console</p>
  <pre><code>WSMessage(type=&lt;WSMsgType.CLOSED: 257&gt;, data=None, extra=None)
  </code></pre>
  <p>While in the server's debug console it says</p>
  <pre><code>INFO:     ('127.0.0.1', 59792) - &quot;WebSocket /ws&quot; [accepted]
  INFO:     connection open
  INFO:     connection closed
  </code></pre>
  <hr />
  <p>When I try to send data from the client to the server</p>
  <p><strong>server</strong></p>
  <pre class="lang-py prettyprint-override"><code>@app.websocket('/ws')
  async def websocket_endpoint(websocket: WebSocket):
      await websocket.accept()
      while True:
          await websocket.receive_text()
  </code></pre>
  <p><strong>client</strong></p>
  <pre class="lang-py prettyprint-override"><code>ws = await s.ws_connect('ws://localhost:8000/ws')
  await ws.send_str('client!')
  </code></pre>
  <p>Nothing happens, I get no message printed out in the server's console, just the debug message saying the client got accepted, connection opened and closed again.</p>
  <hr />
  <p>I have no idea what I'm doing wrong, I followed <a href="https://fastapi.tiangolo.com/advanced/websockets/?h=websocket" rel="nofollow noreferrer">this</a> tutorial in the fastAPI docs for a websocket and the example there with the js websocket works completely fine.</p>