We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Tutorial websocket doc example
**Describe the bug**
Hi, 
On the docs of websocket the last example doesn't work.

**To Reproduce**
Steps to reproduce the behavior:
1. Create a file main.py with the last example on the bottom of the file

>https://fastapi.tiangolo.com/tutorial/websockets/#create-a-websocket
```python
from fastapi import Cookie, Depends, FastAPI, Header
from starlette.responses import HTMLResponse
from starlette.status import WS_1008_POLICY_VIOLATION
from starlette.websockets import WebSocket

app = FastAPI()

html = """
<!DOCTYPE html>
<html>
    <head>
        <title>Chat</title>
    </head>
    <body>
        <h1>WebSocket Chat</h1>
        <form action="" onsubmit="sendMessage(event)">
            <label>Item ID: <input type="text" id="itemId" autocomplete="off" value="foo"/></label>
            <button onclick="connect(event)">Connect</button>
            <br>
            <label>Message: <input type="text" id="messageText" autocomplete="off"/></label>
            <button>Send</button>
        </form>
        <ul id='messages'>
        </ul>
        <script>
        var ws = null;
            function connect(event) {
                var input = document.getElementById("itemId")
                ws = new WebSocket("ws://localhost:8000/items/" + input.value + "/ws");
                ws.onmessage = function(event) {
                    var messages = document.getElementById('messages')
                    var message = document.createElement('li')
                    var content = document.createTextNode(event.data)
                    message.appendChild(content)
                    messages.appendChild(message)
                };
            }
            function sendMessage(event) {
                var input = document.getElementById("messageText")
                ws.send(input.value)
                input.value = ''
                event.preventDefault()
            }
        </script>
    </body>
</html>
"""


@app.get("/")
async def get():
    return HTMLResponse(html)


async def get_cookie_or_client(
    websocket: WebSocket, session: str = Cookie(None), x_client: str = Header(None)
):
    if session is None and x_client is None:
        await websocket.close(code=WS_1008_POLICY_VIOLATION)
    return session or x_client


@app.websocket("/items/{item_id}/ws")
async def websocket_endpoint(
    websocket: WebSocket,
    item_id: int,
    q: str = None,
    cookie_or_client: str = Depends(get_cookie_or_client),
):
    await websocket.accept()
    while True:
        data = await websocket.receive_text()
        await websocket.send_text(
            f"Session Cookie or X-Client Header value is: {cookie_or_client}"
        )
        if q is not None:
            await websocket.send_text(f"Query parameter q is: {q}")
        await websocket.send_text(f"Message text was: {data}, for item ID: {item_id}")
``` 
2. Run the application with the cmd:
```
uvicorn main:app  --log-level debug --reload
```
3. Open the browser 127.0.0.01
  - the first time i connect  with ItemID foo , press the button connect 
  - send message hi with ItemID foo and press the button send.
  it's look like the connect fail but the second ,but the send have return code 200
  but nothing happen on the web side. 

![image](https://user-images.githubusercontent.com/52538873/60673629-db137a00-9e80-11e9-8a6b-8246e5297277.png)

4. See error
```python

INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [366952]
email-validator not installed, email fields will be treated as str.
To install, run: pip install email-validator
INFO: Started server process [366957]
INFO: Waiting for application startup.
DEBUG: None - ASGI [1] Started
DEBUG: None - ASGI [1] Sent {'type': 'lifespan.startup'}
DEBUG: None - ASGI [1] Received {'type': 'lifespan.startup.complete'}
DEBUG: ('127.0.0.1', 50056) - Connected
DEBUG: server - state = CONNECTING
DEBUG: server - event = connection_made(<TCPTransport closed=False reading=True 0x1819178>)
DEBUG: ('127.0.0.1', 50056) - ASGI [2] Started
DEBUG: ('127.0.0.1', 50056) - ASGI [2] Received {'type': 'websocket.close', 'code': 1008}
INFO: ('127.0.0.1', 50056) - "WebSocket /items/foo/ws" 403
DEBUG: ('127.0.0.1', 50056) - ASGI [2] Raised exception
ERROR: Exception in ASGI application
Traceback (most recent call last):
  File "/data/experiments/realtime_web_socket/lib/python3.7/site-packages/uvicorn/protocols/websockets/websockets_impl.py", line 147, in run_asgi
    result = await self.app(self.scope, self.asgi_receive, self.asgi_send)
  File "/data/experiments/realtime_web_socket/lib/python3.7/site-packages/uvicorn/middleware/message_logger.py", line 58, in __call__
    raise exc from None
  File "/data/experiments/realtime_web_socket/lib/python3.7/site-packages/uvicorn/middleware/message_logger.py", line 54, in __call__
    await self.app(scope, inner_receive, inner_send)
  File "/data/experiments/realtime_web_socket/lib/python3.7/site-packages/starlette/applications.py", line 133, in __call__
    await self.error_middleware(scope, receive, send)
  File "/data/experiments/realtime_web_socket/lib/python3.7/site-packages/starlette/middleware/errors.py", line 87, in __call__
    await self.app(scope, receive, send)
  File "/data/experiments/realtime_web_socket/lib/python3.7/site-packages/starlette/exceptions.py", line 49, in __call__
    await self.app(scope, receive, send)
  File "/data/experiments/realtime_web_socket/lib/python3.7/site-packages/starlette/routing.py", line 585, in __call__
    await route(scope, receive, send)
  File "/data/experiments/realtime_web_socket/lib/python3.7/site-packages/starlette/routing.py", line 265, in __call__
    await self.app(scope, receive, send)
  File "/data/experiments/realtime_web_socket/lib/python3.7/site-packages/starlette/routing.py", line 56, in app
    await func(session)
  File "/data/experiments/realtime_web_socket/lib/python3.7/site-packages/fastapi/routing.py", line 148, in app
    await websocket.close(code=WS_1008_POLICY_VIOLATION)
  File "/data/experiments/realtime_web_socket/lib/python3.7/site-packages/starlette/websockets.py", line 121, in close
    await self.send({"type": "websocket.close", "code": code})
  File "/data/experiments/realtime_web_socket/lib/python3.7/site-packages/starlette/websockets.py", line 70, in send
    raise RuntimeError('Cannot call "send" once a close message has been sent.')
RuntimeError: Cannot call "send" once a close message has been sent.
DEBUG: server ! failing WebSocket connection in the CONNECTING state: 1006 [no reason]
DEBUG: ('127.0.0.1', 50058) - Connected
DEBUG: server x half-closing TCP connection
DEBUG: ('127.0.0.1', 50058) - ASGI [3] Started
DEBUG: ('127.0.0.1', 50058) - ASGI [3] Received {'type': 'http.response.start', 'status': 200, 'headers': '<...>'}
INFO: ('127.0.0.1', 50058) - "GET / HTTP/1.1" 200
DEBUG: ('127.0.0.1', 50058) - ASGI [3] Received {'type': 'http.response.body', 'body': '<1419 bytes>'}
DEBUG: ('127.0.0.1', 50058) - ASGI [3] Completed
DEBUG: server - event = eof_received()
DEBUG: server - event = connection_lost(None)
DEBUG: server - state = CLOSED
DEBUG: server x code = 1006, reason = [no reason]
DEBUG: ('127.0.0.1', 50058) - Disconnected
DEBUG: ('127.0.0.1', 50060) - Connected
DEBUG: ('127.0.0.1', 50060) - ASGI [4] Started
DEBUG: ('127.0.0.1', 50060) - ASGI [4] Received {'type': 'http.response.start', 'status': 200, 'headers': '<...>'}
INFO: ('127.0.0.1', 50060) - "GET / HTTP/1.1" 200
DEBUG: ('127.0.0.1', 50060) - ASGI [4] Received {'type': 'http.response.body', 'body': '<1419 bytes>'}
DEBUG: ('127.0.0.1', 50060) - ASGI [4] Completed
DEBUG: ('127.0.0.1', 50060) - Disconnected


```
**Expected behavior**
expected to appear the send  bold message  on the web page.

**Environment:**
 - OS: centos 7
 - FastAPI Version [e.g. 0.3.0], get it with: fastapi==0.31.0

```Python
import fastapi
print(fastapi.__version__)
0.31.0
```

- Python version, get it with:

```bash
python --version
Python 3.7.3
```



--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `docs_src/websockets/tutorial002.py`
Content:
```
1 from fastapi import Cookie, Depends, FastAPI, Header, WebSocket, status
2 from fastapi.responses import HTMLResponse
3 
4 app = FastAPI()
5 
6 html = """
7 <!DOCTYPE html>
8 <html>
9     <head>
10         <title>Chat</title>
11     </head>
12     <body>
13         <h1>WebSocket Chat</h1>
14         <form action="" onsubmit="sendMessage(event)">
15             <label>Item ID: <input type="text" id="itemId" autocomplete="off" value="foo"/></label>
16             <button onclick="connect(event)">Connect</button>
17             <br>
18             <label>Message: <input type="text" id="messageText" autocomplete="off"/></label>
19             <button>Send</button>
20         </form>
21         <ul id='messages'>
22         </ul>
23         <script>
24         var ws = null;
25             function connect(event) {
26                 var input = document.getElementById("itemId")
27                 ws = new WebSocket("ws://localhost:8000/items/" + input.value + "/ws");
28                 ws.onmessage = function(event) {
29                     var messages = document.getElementById('messages')
30                     var message = document.createElement('li')
31                     var content = document.createTextNode(event.data)
32                     message.appendChild(content)
33                     messages.appendChild(message)
34                 };
35             }
36             function sendMessage(event) {
37                 var input = document.getElementById("messageText")
38                 ws.send(input.value)
39                 input.value = ''
40                 event.preventDefault()
41             }
42         </script>
43     </body>
44 </html>
45 """
46 
47 
48 @app.get("/")
49 async def get():
50     return HTMLResponse(html)
51 
52 
53 async def get_cookie_or_client(
54     websocket: WebSocket, session: str = Cookie(None), x_client: str = Header(None)
55 ):
56     if session is None and x_client is None:
57         await websocket.close(code=status.WS_1008_POLICY_VIOLATION)
58     return session or x_client
59 
60 
61 @app.websocket("/items/{item_id}/ws")
62 async def websocket_endpoint(
63     websocket: WebSocket,
64     item_id: int,
65     q: str = None,
66     cookie_or_client: str = Depends(get_cookie_or_client),
67 ):
68     await websocket.accept()
69     while True:
70         data = await websocket.receive_text()
71         await websocket.send_text(
72             f"Session Cookie or X-Client Header value is: {cookie_or_client}"
73         )
74         if q is not None:
75             await websocket.send_text(f"Query parameter q is: {q}")
76         await websocket.send_text(f"Message text was: {data}, for item ID: {item_id}")
77
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/docs_src/websockets/tutorial002.py b/docs_src/websockets/tutorial002.py
--- a/docs_src/websockets/tutorial002.py
+++ b/docs_src/websockets/tutorial002.py
@@ -1,4 +1,4 @@
-from fastapi import Cookie, Depends, FastAPI, Header, WebSocket, status
+from fastapi import Cookie, Depends, FastAPI, Query, WebSocket, status
 from fastapi.responses import HTMLResponse
 
 app = FastAPI()
@@ -13,8 +13,9 @@
         <h1>WebSocket Chat</h1>
         <form action="" onsubmit="sendMessage(event)">
             <label>Item ID: <input type="text" id="itemId" autocomplete="off" value="foo"/></label>
+            <label>Token: <input type="text" id="token" autocomplete="off" value="some-key-token"/></label>
             <button onclick="connect(event)">Connect</button>
-            <br>
+            <hr>
             <label>Message: <input type="text" id="messageText" autocomplete="off"/></label>
             <button>Send</button>
         </form>
@@ -23,8 +24,9 @@
         <script>
         var ws = null;
             function connect(event) {
-                var input = document.getElementById("itemId")
-                ws = new WebSocket("ws://localhost:8000/items/" + input.value + "/ws");
+                var itemId = document.getElementById("itemId")
+                var token = document.getElementById("token")
+                ws = new WebSocket("ws://localhost:8000/items/" + itemId.value + "/ws?token=" + token.value);
                 ws.onmessage = function(event) {
                     var messages = document.getElementById('messages')
                     var message = document.createElement('li')
@@ -32,6 +34,7 @@
                     message.appendChild(content)
                     messages.appendChild(message)
                 };
+                event.preventDefault()
             }
             function sendMessage(event) {
                 var input = document.getElementById("messageText")
@@ -50,26 +53,26 @@
     return HTMLResponse(html)
 
 
-async def get_cookie_or_client(
-    websocket: WebSocket, session: str = Cookie(None), x_client: str = Header(None)
+async def get_cookie_or_token(
+    websocket: WebSocket, session: str = Cookie(None), token: str = Query(None)
 ):
-    if session is None and x_client is None:
+    if session is None and token is None:
         await websocket.close(code=status.WS_1008_POLICY_VIOLATION)
-    return session or x_client
+    return session or token
 
 
 @app.websocket("/items/{item_id}/ws")
 async def websocket_endpoint(
     websocket: WebSocket,
-    item_id: int,
-    q: str = None,
-    cookie_or_client: str = Depends(get_cookie_or_client),
+    item_id: str,
+    q: int = None,
+    cookie_or_token: str = Depends(get_cookie_or_token),
 ):
     await websocket.accept()
     while True:
         data = await websocket.receive_text()
         await websocket.send_text(
-            f"Session Cookie or X-Client Header value is: {cookie_or_client}"
+            f"Session cookie or query token value is: {cookie_or_token}"
         )
         if q is not None:
             await websocket.send_text(f"Query parameter q is: {q}")

{"golden_diff": "diff --git a/docs_src/websockets/tutorial002.py b/docs_src/websockets/tutorial002.py\n--- a/docs_src/websockets/tutorial002.py\n+++ b/docs_src/websockets/tutorial002.py\n@@ -1,4 +1,4 @@\n-from fastapi import Cookie, Depends, FastAPI, Header, WebSocket, status\n+from fastapi import Cookie, Depends, FastAPI, Query, WebSocket, status\n from fastapi.responses import HTMLResponse\n \n app = FastAPI()\n@@ -13,8 +13,9 @@\n         <h1>WebSocket Chat</h1>\n         <form action=\"\" onsubmit=\"sendMessage(event)\">\n             <label>Item ID: <input type=\"text\" id=\"itemId\" autocomplete=\"off\" value=\"foo\"/></label>\n+            <label>Token: <input type=\"text\" id=\"token\" autocomplete=\"off\" value=\"some-key-token\"/></label>\n             <button onclick=\"connect(event)\">Connect</button>\n-            <br>\n+            <hr>\n             <label>Message: <input type=\"text\" id=\"messageText\" autocomplete=\"off\"/></label>\n             <button>Send</button>\n         </form>\n@@ -23,8 +24,9 @@\n         <script>\n         var ws = null;\n             function connect(event) {\n-                var input = document.getElementById(\"itemId\")\n-                ws = new WebSocket(\"ws://localhost:8000/items/\" + input.value + \"/ws\");\n+                var itemId = document.getElementById(\"itemId\")\n+                var token = document.getElementById(\"token\")\n+                ws = new WebSocket(\"ws://localhost:8000/items/\" + itemId.value + \"/ws?token=\" + token.value);\n                 ws.onmessage = function(event) {\n                     var messages = document.getElementById('messages')\n                     var message = document.createElement('li')\n@@ -32,6 +34,7 @@\n                     message.appendChild(content)\n                     messages.appendChild(message)\n                 };\n+                event.preventDefault()\n             }\n             function sendMessage(event) {\n                 var input = document.getElementById(\"messageText\")\n@@ -50,26 +53,26 @@\n     return HTMLResponse(html)\n \n \n-async def get_cookie_or_client(\n-    websocket: WebSocket, session: str = Cookie(None), x_client: str = Header(None)\n+async def get_cookie_or_token(\n+    websocket: WebSocket, session: str = Cookie(None), token: str = Query(None)\n ):\n-    if session is None and x_client is None:\n+    if session is None and token is None:\n         await websocket.close(code=status.WS_1008_POLICY_VIOLATION)\n-    return session or x_client\n+    return session or token\n \n \n @app.websocket(\"/items/{item_id}/ws\")\n async def websocket_endpoint(\n     websocket: WebSocket,\n-    item_id: int,\n-    q: str = None,\n-    cookie_or_client: str = Depends(get_cookie_or_client),\n+    item_id: str,\n+    q: int = None,\n+    cookie_or_token: str = Depends(get_cookie_or_token),\n ):\n     await websocket.accept()\n     while True:\n         data = await websocket.receive_text()\n         await websocket.send_text(\n-            f\"Session Cookie or X-Client Header value is: {cookie_or_client}\"\n+            f\"Session cookie or query token value is: {cookie_or_token}\"\n         )\n         if q is not None:\n             await websocket.send_text(f\"Query parameter q is: {q}\")\n", "issue": "Tutorial websocket doc example\n**Describe the bug**\r\nHi, \r\nOn the docs of websocket the last example doesn't work.\r\n\r\n**To Reproduce**\r\nSteps to reproduce the behavior:\r\n1. Create a file main.py with the last example on the bottom of the file\r\n\r\n>https://fastapi.tiangolo.com/tutorial/websockets/#create-a-websocket\r\n```python\r\nfrom fastapi import Cookie, Depends, FastAPI, Header\r\nfrom starlette.responses import HTMLResponse\r\nfrom starlette.status import WS_1008_POLICY_VIOLATION\r\nfrom starlette.websockets import WebSocket\r\n\r\napp = FastAPI()\r\n\r\nhtml = \"\"\"\r\n<!DOCTYPE html>\r\n<html>\r\n    <head>\r\n        <title>Chat</title>\r\n    </head>\r\n    <body>\r\n        <h1>WebSocket Chat</h1>\r\n        <form action=\"\" onsubmit=\"sendMessage(event)\">\r\n            <label>Item ID: <input type=\"text\" id=\"itemId\" autocomplete=\"off\" value=\"foo\"/></label>\r\n            <button onclick=\"connect(event)\">Connect</button>\r\n            <br>\r\n            <label>Message: <input type=\"text\" id=\"messageText\" autocomplete=\"off\"/></label>\r\n            <button>Send</button>\r\n        </form>\r\n        <ul id='messages'>\r\n        </ul>\r\n        <script>\r\n        var ws = null;\r\n            function connect(event) {\r\n                var input = document.getElementById(\"itemId\")\r\n                ws = new WebSocket(\"ws://localhost:8000/items/\" + input.value + \"/ws\");\r\n                ws.onmessage = function(event) {\r\n                    var messages = document.getElementById('messages')\r\n                    var message = document.createElement('li')\r\n                    var content = document.createTextNode(event.data)\r\n                    message.appendChild(content)\r\n                    messages.appendChild(message)\r\n                };\r\n            }\r\n            function sendMessage(event) {\r\n                var input = document.getElementById(\"messageText\")\r\n                ws.send(input.value)\r\n                input.value = ''\r\n                event.preventDefault()\r\n            }\r\n        </script>\r\n    </body>\r\n</html>\r\n\"\"\"\r\n\r\n\r\n@app.get(\"/\")\r\nasync def get():\r\n    return HTMLResponse(html)\r\n\r\n\r\nasync def get_cookie_or_client(\r\n    websocket: WebSocket, session: str = Cookie(None), x_client: str = Header(None)\r\n):\r\n    if session is None and x_client is None:\r\n        await websocket.close(code=WS_1008_POLICY_VIOLATION)\r\n    return session or x_client\r\n\r\n\r\n@app.websocket(\"/items/{item_id}/ws\")\r\nasync def websocket_endpoint(\r\n    websocket: WebSocket,\r\n    item_id: int,\r\n    q: str = None,\r\n    cookie_or_client: str = Depends(get_cookie_or_client),\r\n):\r\n    await websocket.accept()\r\n    while True:\r\n        data = await websocket.receive_text()\r\n        await websocket.send_text(\r\n            f\"Session Cookie or X-Client Header value is: {cookie_or_client}\"\r\n        )\r\n        if q is not None:\r\n            await websocket.send_text(f\"Query parameter q is: {q}\")\r\n        await websocket.send_text(f\"Message text was: {data}, for item ID: {item_id}\")\r\n``` \r\n2. Run the application with the cmd:\r\n```\r\nuvicorn main:app  --log-level debug --reload\r\n```\r\n3. Open the browser 127.0.0.01\r\n  - the first time i connect  with ItemID foo , press the button connect \r\n  - send message hi with ItemID foo and press the button send.\r\n  it's look like the connect fail but the second ,but the send have return code 200\r\n  but nothing happen on the web side. \r\n\r\n![image](https://user-images.githubusercontent.com/52538873/60673629-db137a00-9e80-11e9-8a6b-8246e5297277.png)\r\n\r\n4. See error\r\n```python\r\n\r\nINFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)\r\nINFO: Started reloader process [366952]\r\nemail-validator not installed, email fields will be treated as str.\r\nTo install, run: pip install email-validator\r\nINFO: Started server process [366957]\r\nINFO: Waiting for application startup.\r\nDEBUG: None - ASGI [1] Started\r\nDEBUG: None - ASGI [1] Sent {'type': 'lifespan.startup'}\r\nDEBUG: None - ASGI [1] Received {'type': 'lifespan.startup.complete'}\r\nDEBUG: ('127.0.0.1', 50056) - Connected\r\nDEBUG: server - state = CONNECTING\r\nDEBUG: server - event = connection_made(<TCPTransport closed=False reading=True 0x1819178>)\r\nDEBUG: ('127.0.0.1', 50056) - ASGI [2] Started\r\nDEBUG: ('127.0.0.1', 50056) - ASGI [2] Received {'type': 'websocket.close', 'code': 1008}\r\nINFO: ('127.0.0.1', 50056) - \"WebSocket /items/foo/ws\" 403\r\nDEBUG: ('127.0.0.1', 50056) - ASGI [2] Raised exception\r\nERROR: Exception in ASGI application\r\nTraceback (most recent call last):\r\n  File \"/data/experiments/realtime_web_socket/lib/python3.7/site-packages/uvicorn/protocols/websockets/websockets_impl.py\", line 147, in run_asgi\r\n    result = await self.app(self.scope, self.asgi_receive, self.asgi_send)\r\n  File \"/data/experiments/realtime_web_socket/lib/python3.7/site-packages/uvicorn/middleware/message_logger.py\", line 58, in __call__\r\n    raise exc from None\r\n  File \"/data/experiments/realtime_web_socket/lib/python3.7/site-packages/uvicorn/middleware/message_logger.py\", line 54, in __call__\r\n    await self.app(scope, inner_receive, inner_send)\r\n  File \"/data/experiments/realtime_web_socket/lib/python3.7/site-packages/starlette/applications.py\", line 133, in __call__\r\n    await self.error_middleware(scope, receive, send)\r\n  File \"/data/experiments/realtime_web_socket/lib/python3.7/site-packages/starlette/middleware/errors.py\", line 87, in __call__\r\n    await self.app(scope, receive, send)\r\n  File \"/data/experiments/realtime_web_socket/lib/python3.7/site-packages/starlette/exceptions.py\", line 49, in __call__\r\n    await self.app(scope, receive, send)\r\n  File \"/data/experiments/realtime_web_socket/lib/python3.7/site-packages/starlette/routing.py\", line 585, in __call__\r\n    await route(scope, receive, send)\r\n  File \"/data/experiments/realtime_web_socket/lib/python3.7/site-packages/starlette/routing.py\", line 265, in __call__\r\n    await self.app(scope, receive, send)\r\n  File \"/data/experiments/realtime_web_socket/lib/python3.7/site-packages/starlette/routing.py\", line 56, in app\r\n    await func(session)\r\n  File \"/data/experiments/realtime_web_socket/lib/python3.7/site-packages/fastapi/routing.py\", line 148, in app\r\n    await websocket.close(code=WS_1008_POLICY_VIOLATION)\r\n  File \"/data/experiments/realtime_web_socket/lib/python3.7/site-packages/starlette/websockets.py\", line 121, in close\r\n    await self.send({\"type\": \"websocket.close\", \"code\": code})\r\n  File \"/data/experiments/realtime_web_socket/lib/python3.7/site-packages/starlette/websockets.py\", line 70, in send\r\n    raise RuntimeError('Cannot call \"send\" once a close message has been sent.')\r\nRuntimeError: Cannot call \"send\" once a close message has been sent.\r\nDEBUG: server ! failing WebSocket connection in the CONNECTING state: 1006 [no reason]\r\nDEBUG: ('127.0.0.1', 50058) - Connected\r\nDEBUG: server x half-closing TCP connection\r\nDEBUG: ('127.0.0.1', 50058) - ASGI [3] Started\r\nDEBUG: ('127.0.0.1', 50058) - ASGI [3] Received {'type': 'http.response.start', 'status': 200, 'headers': '<...>'}\r\nINFO: ('127.0.0.1', 50058) - \"GET / HTTP/1.1\" 200\r\nDEBUG: ('127.0.0.1', 50058) - ASGI [3] Received {'type': 'http.response.body', 'body': '<1419 bytes>'}\r\nDEBUG: ('127.0.0.1', 50058) - ASGI [3] Completed\r\nDEBUG: server - event = eof_received()\r\nDEBUG: server - event = connection_lost(None)\r\nDEBUG: server - state = CLOSED\r\nDEBUG: server x code = 1006, reason = [no reason]\r\nDEBUG: ('127.0.0.1', 50058) - Disconnected\r\nDEBUG: ('127.0.0.1', 50060) - Connected\r\nDEBUG: ('127.0.0.1', 50060) - ASGI [4] Started\r\nDEBUG: ('127.0.0.1', 50060) - ASGI [4] Received {'type': 'http.response.start', 'status': 200, 'headers': '<...>'}\r\nINFO: ('127.0.0.1', 50060) - \"GET / HTTP/1.1\" 200\r\nDEBUG: ('127.0.0.1', 50060) - ASGI [4] Received {'type': 'http.response.body', 'body': '<1419 bytes>'}\r\nDEBUG: ('127.0.0.1', 50060) - ASGI [4] Completed\r\nDEBUG: ('127.0.0.1', 50060) - Disconnected\r\n\r\n\r\n```\r\n**Expected behavior**\r\nexpected to appear the send  bold message  on the web page.\r\n\r\n**Environment:**\r\n - OS: centos 7\r\n - FastAPI Version [e.g. 0.3.0], get it with: fastapi==0.31.0\r\n\r\n```Python\r\nimport fastapi\r\nprint(fastapi.__version__)\r\n0.31.0\r\n```\r\n\r\n- Python version, get it with:\r\n\r\n```bash\r\npython --version\r\nPython 3.7.3\r\n```\r\n\r\n\n", "before_files": [{"content": "from fastapi import Cookie, Depends, FastAPI, Header, WebSocket, status\nfrom fastapi.responses import HTMLResponse\n\napp = FastAPI()\n\nhtml = \"\"\"\n<!DOCTYPE html>\n<html>\n    <head>\n        <title>Chat</title>\n    </head>\n    <body>\n        <h1>WebSocket Chat</h1>\n        <form action=\"\" onsubmit=\"sendMessage(event)\">\n            <label>Item ID: <input type=\"text\" id=\"itemId\" autocomplete=\"off\" value=\"foo\"/></label>\n            <button onclick=\"connect(event)\">Connect</button>\n            <br>\n            <label>Message: <input type=\"text\" id=\"messageText\" autocomplete=\"off\"/></label>\n            <button>Send</button>\n        </form>\n        <ul id='messages'>\n        </ul>\n        <script>\n        var ws = null;\n            function connect(event) {\n                var input = document.getElementById(\"itemId\")\n                ws = new WebSocket(\"ws://localhost:8000/items/\" + input.value + \"/ws\");\n                ws.onmessage = function(event) {\n                    var messages = document.getElementById('messages')\n                    var message = document.createElement('li')\n                    var content = document.createTextNode(event.data)\n                    message.appendChild(content)\n                    messages.appendChild(message)\n                };\n            }\n            function sendMessage(event) {\n                var input = document.getElementById(\"messageText\")\n                ws.send(input.value)\n                input.value = ''\n                event.preventDefault()\n            }\n        </script>\n    </body>\n</html>\n\"\"\"\n\n\n@app.get(\"/\")\nasync def get():\n    return HTMLResponse(html)\n\n\nasync def get_cookie_or_client(\n    websocket: WebSocket, session: str = Cookie(None), x_client: str = Header(None)\n):\n    if session is None and x_client is None:\n        await websocket.close(code=status.WS_1008_POLICY_VIOLATION)\n    return session or x_client\n\n\n@app.websocket(\"/items/{item_id}/ws\")\nasync def websocket_endpoint(\n    websocket: WebSocket,\n    item_id: int,\n    q: str = None,\n    cookie_or_client: str = Depends(get_cookie_or_client),\n):\n    await websocket.accept()\n    while True:\n        data = await websocket.receive_text()\n        await websocket.send_text(\n            f\"Session Cookie or X-Client Header value is: {cookie_or_client}\"\n        )\n        if q is not None:\n            await websocket.send_text(f\"Query parameter q is: {q}\")\n        await websocket.send_text(f\"Message text was: {data}, for item ID: {item_id}\")\n", "path": "docs_src/websockets/tutorial002.py"}], "after_files": [{"content": "from fastapi import Cookie, Depends, FastAPI, Query, WebSocket, status\nfrom fastapi.responses import HTMLResponse\n\napp = FastAPI()\n\nhtml = \"\"\"\n<!DOCTYPE html>\n<html>\n    <head>\n        <title>Chat</title>\n    </head>\n    <body>\n        <h1>WebSocket Chat</h1>\n        <form action=\"\" onsubmit=\"sendMessage(event)\">\n            <label>Item ID: <input type=\"text\" id=\"itemId\" autocomplete=\"off\" value=\"foo\"/></label>\n            <label>Token: <input type=\"text\" id=\"token\" autocomplete=\"off\" value=\"some-key-token\"/></label>\n            <button onclick=\"connect(event)\">Connect</button>\n            <hr>\n            <label>Message: <input type=\"text\" id=\"messageText\" autocomplete=\"off\"/></label>\n            <button>Send</button>\n        </form>\n        <ul id='messages'>\n        </ul>\n        <script>\n        var ws = null;\n            function connect(event) {\n                var itemId = document.getElementById(\"itemId\")\n                var token = document.getElementById(\"token\")\n                ws = new WebSocket(\"ws://localhost:8000/items/\" + itemId.value + \"/ws?token=\" + token.value);\n                ws.onmessage = function(event) {\n                    var messages = document.getElementById('messages')\n                    var message = document.createElement('li')\n                    var content = document.createTextNode(event.data)\n                    message.appendChild(content)\n                    messages.appendChild(message)\n                };\n                event.preventDefault()\n            }\n            function sendMessage(event) {\n                var input = document.getElementById(\"messageText\")\n                ws.send(input.value)\n                input.value = ''\n                event.preventDefault()\n            }\n        </script>\n    </body>\n</html>\n\"\"\"\n\n\n@app.get(\"/\")\nasync def get():\n    return HTMLResponse(html)\n\n\nasync def get_cookie_or_token(\n    websocket: WebSocket, session: str = Cookie(None), token: str = Query(None)\n):\n    if session is None and token is None:\n        await websocket.close(code=status.WS_1008_POLICY_VIOLATION)\n    return session or token\n\n\n@app.websocket(\"/items/{item_id}/ws\")\nasync def websocket_endpoint(\n    websocket: WebSocket,\n    item_id: str,\n    q: int = None,\n    cookie_or_token: str = Depends(get_cookie_or_token),\n):\n    await websocket.accept()\n    while True:\n        data = await websocket.receive_text()\n        await websocket.send_text(\n            f\"Session cookie or query token value is: {cookie_or_token}\"\n        )\n        if q is not None:\n            await websocket.send_text(f\"Query parameter q is: {q}\")\n        await websocket.send_text(f\"Message text was: {data}, for item ID: {item_id}\")\n", "path": "docs_src/websockets/tutorial002.py"}]}