diff --git a/tornado/websocket.py b/tornado/websocket.py
index d5a7fa89..c6804ca0 100644
--- a/tornado/websocket.py
+++ b/tornado/websocket.py
@@ -616,6 +616,14 @@ class WebSocketProtocol13(WebSocketProtocol):
     def accept_connection(self):
         try:
             self._handle_websocket_headers()
+        except ValueError:
+            self.handler.set_status(400)
+            log_msg = "Missing/Invalid WebSocket headers"
+            self.handler.finish(log_msg)
+            gen_log.debug(log_msg)
+            return
+
+        try:
             self._accept_connection()
         except ValueError:
             gen_log.debug("Malformed WebSocket request received",

AttributeError if Websocket client misses required header
If the client misses required header for websocket handshake, the server raises AttributeError.

Minimal code for reproduce

### Client

```python
import socket

REQ_1 = ('GET /ws HTTP/1.1\r\n'
         'Host: example.com:9221\r\n'
         'Upgrade: websocket\r\n'
         'Connection: Upgrade\r\n'
        #  'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n'
         'Sec-WebSocket-Version: 13\r\n'
         '\r\n')
conn = socket.create_connection(('127.0.0.1', 9221))
conn.send(REQ_1.encode('utf-8'))
resp_1 = conn.recv(10 * 1024)
```

### Server

```python
import tornado.ioloop
import tornado.web
import tornado.websocket

class WsHandler(tornado.websocket.WebSocketHandler):
    pass

def make_app():
    return tornado.web.Application([
        (r'/ws', WsHandler),
    ])

if __name__ == "__main__":
    app = make_app()
    app.listen(9221)
    tornado.ioloop.IOLoop.current().start()
```

### Traceback

```
ERROR:tornado.application:Uncaught exception GET /ws (127.0.0.1)
HTTPServerRequest(protocol='http', host='example.com:8000', method='GET', uri='/ws', version='HTTP/1.1', remote_ip='127.0.0.1', headers={'Host': 'example.com:8000', 'Upgrade': 'websocket', 'Connection': 'Upgrade', 'Sec-Websocket-Version': '13'})
Traceback (most recent call last):
  File "/home/pjknkda/test/ws-invalid/python-env/lib/python3.6/site-packages/tornado/websocket.py", line 618, in accept_connection
    self._handle_websocket_headers()
  File "/home/pjknkda/test/ws-invalid/python-env/lib/python3.6/site-packages/tornado/websocket.py", line 634, in _handle_websocket_headers
    raise ValueError("Missing/Invalid WebSocket headers")
ValueError: Missing/Invalid WebSocket headers

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/pjknkda/test/ws-invalid/python-env/lib/python3.6/site-packages/tornado/web.py", line 1467, in _stack_context_handle_exception
    raise_exc_info((type, value, traceback))
  File "<string>", line 4, in raise_exc_info
  File "/home/pjknkda/test/ws-invalid/python-env/lib/python3.6/site-packages/tornado/web.py", line 1669, in wrapper
    result = method(self, *args, **kwargs)
  File "/home/pjknkda/test/ws-invalid/python-env/lib/python3.6/site-packages/tornado/websocket.py", line 196, in get
    self.ws_connection.accept_connection()
  File "/home/pjknkda/test/ws-invalid/python-env/lib/python3.6/site-packages/tornado/websocket.py", line 623, in accept_connection
    self._abort()
  File "/home/pjknkda/test/ws-invalid/python-env/lib/python3.6/site-packages/tornado/websocket.py", line 512, in _abort
    self.stream.close()  # forcibly tear down the connection
AttributeError: 'NoneType' object has no attribute 'close'
ERROR:tornado.access:500 GET /ws (127.0.0.1) 4.13ms
```

It seems that `WebSocketProtocol13.accept_connection` calls `WebSocketProtocol._abort` immediately if there is missing required headers, however, it is before the handshake, thus there is yet no `self.stream` whereas the _abort function tries to `self.stream.close()`. Also, the _abort function calls `self.close()` and there is also the same buggy code which calls `self.stream.close()` without checking the nullity of `self.stream`.
diff --git a/tornado/test/websocket_test.py b/tornado/test/websocket_test.py
index 5a2a6577..54734d81 100644
--- a/tornado/test/websocket_test.py
+++ b/tornado/test/websocket_test.py
@@ -193,6 +193,13 @@ class WebSocketTest(WebSocketBaseTestCase):
         response = self.fetch('/echo')
         self.assertEqual(response.code, 400)
 
+    def test_missing_websocket_key(self):
+        response = self.fetch('/echo',
+                              headers={'Connection': 'Upgrade',
+                                       'Upgrade': 'WebSocket',
+                                       'Sec-WebSocket-Version': '13'})
+        self.assertEqual(response.code, 400)
+
     def test_bad_websocket_version(self):
         response = self.fetch('/echo',
                               headers={'Connection': 'Upgrade',

pip install -e .[dev]
parse_log_pytest
requirements.txt
sphinx sphinx_rtd_theme codecov virtualenv pytest
apt-get update apt-get install -y gcc
3.6
requirements/base.txt
pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning
alabaster==0.7.13
attrs==22.2.0
Babel==2.11.0
certifi==2021.5.30
charset-normalizer==2.0.12
codecov==2.1.13
coverage==6.2
distlib==0.3.9
docutils==0.18.1
filelock==3.4.1
idna==3.10
imagesize==1.4.1
importlib-metadata==4.8.3
importlib-resources==5.4.0
iniconfig==1.1.1
Jinja2==3.0.3
MarkupSafe==2.0.1
packaging==21.3
platformdirs==2.4.0
pluggy==1.0.0
py==1.11.0
Pygments==2.14.0
pyparsing==3.1.4
pytest==7.0.1
pytz==2025.2
requests==2.27.1
snowballstemmer==2.2.0
Sphinx==5.3.0
sphinx-rtd-theme==2.0.0
sphinxcontrib-applehelp==1.0.2
sphinxcontrib-devhelp==1.0.2
sphinxcontrib-htmlhelp==2.0.0
sphinxcontrib-jquery==4.1
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==1.0.3
sphinxcontrib-serializinghtml==1.1.5
tomli==1.2.3
-e git+https://github.com/tornadoweb/tornado.git@34c43f4775971ab9b2b8ed43356f218add6387b2#egg=tornado
typing_extensions==4.1.1
urllib3==1.26.20
virtualenv==20.17.1
zipp==3.6.0

name: tornado
channels:
  - defaults
  - https://repo.anaconda.com/pkgs/main
  - https://repo.anaconda.com/pkgs/r
  - conda-forge
dependencies:
  - _libgcc_mutex=0.1=main
  - _openmp_mutex=5.1=1_gnu
  - ca-certificates=2025.2.25=h06a4308_0
  - certifi=2021.5.30=py36h06a4308_0
  - ld_impl_linux-64=2.40=h12ee557_0
  - libffi=3.3=he6710b0_2
  - libgcc-ng=11.2.0=h1234567_1
  - libgomp=11.2.0=h1234567_1
  - libstdcxx-ng=11.2.0=h1234567_1
  - ncurses=6.4=h6a678d5_0
  - openssl=1.1.1w=h7f8727e_0
  - pip=21.2.2=py36h06a4308_0
  - python=3.6.13=h12debd9_1
  - readline=8.2=h5eee18b_0
  - setuptools=58.0.4=py36h06a4308_0
  - sqlite=3.45.3=h5eee18b_0
  - tk=8.6.14=h39e8969_0
  - wheel=0.37.1=pyhd3eb1b0_0
  - xz=5.6.4=h5eee18b_1
  - zlib=1.2.13=h5eee18b_1
  - pip:
      - alabaster==0.7.13
      - attrs==22.2.0
      - babel==2.11.0
      - charset-normalizer==2.0.12
      - codecov==2.1.13
      - coverage==6.2
      - distlib==0.3.9
      - docutils==0.18.1
      - filelock==3.4.1
      - idna==3.10
      - imagesize==1.4.1
      - importlib-metadata==4.8.3
      - importlib-resources==5.4.0
      - iniconfig==1.1.1
      - jinja2==3.0.3
      - markupsafe==2.0.1
      - packaging==21.3
      - platformdirs==2.4.0
      - pluggy==1.0.0
      - py==1.11.0
      - pygments==2.14.0
      - pyparsing==3.1.4
      - pytest==7.0.1
      - pytz==2025.2
      - requests==2.27.1
      - snowballstemmer==2.2.0
      - sphinx==5.3.0
      - sphinx-rtd-theme==2.0.0
      - sphinxcontrib-applehelp==1.0.2
      - sphinxcontrib-devhelp==1.0.2
      - sphinxcontrib-htmlhelp==2.0.0
      - sphinxcontrib-jquery==4.1
      - sphinxcontrib-jsmath==1.0.1
      - sphinxcontrib-qthelp==1.0.3
      - sphinxcontrib-serializinghtml==1.1.5
      - tomli==1.2.3
      - typing-extensions==4.1.1
      - urllib3==1.26.20
      - virtualenv==20.17.1
      - zipp==3.6.0
prefix: /opt/conda/envs/tornado

tornado/test/websocket_test.py::WebSocketTest::test_missing_websocket_key
tornado/test/websocket_test.py::WebSocketTest::test_async_prepare tornado/test/websocket_test.py::WebSocketTest::test_bad_websocket_version tornado/test/websocket_test.py::WebSocketTest::test_binary_message tornado/test/websocket_test.py::WebSocketTest::test_check_origin_invalid tornado/test/websocket_test.py::WebSocketTest::test_check_origin_invalid_partial_url tornado/test/websocket_test.py::WebSocketTest::test_check_origin_invalid_subdomains tornado/test/websocket_test.py::WebSocketTest::test_check_origin_valid_no_path tornado/test/websocket_test.py::WebSocketTest::test_check_origin_valid_with_path tornado/test/websocket_test.py::WebSocketTest::test_client_close_reason tornado/test/websocket_test.py::WebSocketTest::test_coroutine tornado/test/websocket_test.py::WebSocketTest::test_error_in_on_message tornado/test/websocket_test.py::WebSocketTest::test_http_request tornado/test/websocket_test.py::WebSocketTest::test_path_args tornado/test/websocket_test.py::WebSocketTest::test_render_message tornado/test/websocket_test.py::WebSocketTest::test_server_close_reason tornado/test/websocket_test.py::WebSocketTest::test_unicode_message tornado/test/websocket_test.py::WebSocketTest::test_websocket_callbacks tornado/test/websocket_test.py::WebSocketTest::test_websocket_close_buffered_data tornado/test/websocket_test.py::WebSocketTest::test_websocket_gen tornado/test/websocket_test.py::WebSocketTest::test_websocket_header_echo tornado/test/websocket_test.py::WebSocketTest::test_websocket_headers tornado/test/websocket_test.py::WebSocketTest::test_websocket_http_fail tornado/test/websocket_test.py::WebSocketTest::test_websocket_http_success tornado/test/websocket_test.py::WebSocketTest::test_websocket_network_fail tornado/test/websocket_test.py::WebSocketTest::test_write_after_close tornado/test/websocket_test.py::WebSocketNativeCoroutineTest::test_native_coroutine tornado/test/websocket_test.py::NoCompressionTest::test_message_sizes tornado/test/websocket_test.py::ServerOnlyCompressionTest::test_message_sizes tornado/test/websocket_test.py::ClientOnlyCompressionTest::test_message_sizes tornado/test/websocket_test.py::DefaultCompressionTest::test_message_sizes tornado/test/websocket_test.py::PythonMaskFunctionTest::test_mask tornado/test/websocket_test.py::CythonMaskFunctionTest::test_mask tornado/test/websocket_test.py::ServerPeriodicPingTest::test_server_ping tornado/test/websocket_test.py::ClientPeriodicPingTest::test_client_ping tornado/test/websocket_test.py::MaxMessageSizeTest::test_large_message
tornado/websocket.py
tornado/websocket.py