


What is the reason why the browser does not respond after the WebSocket server returns 401? How to solve it?
Netty WebSocket server returns 401, browser unresponsive solution
When using Netty to build a WebSocket server and perform token verification, if the token is invalid, the server returns a 401 status code and closes the connection, but the browser may not react in any way. This article analyzes this problem and provides solutions.
Problem description
Tokens are required to develop WebSocket servers using Netty. When token verification fails, the server returns 401 and closes the connection, but the browser does not respond, and the front-end cannot know the reason for the connection to close. Server-side code example:
private void httpResponse401(ChannelHandlerContext ctx, FullHttpRequest request) { FullHttpResponse response = new DefaultFullHttpResponse(request.protocolVersion(), HttpResponseStatus.UNAUTHORIZED); response.headers().set(HttpHeaderNames.CONTENT_LENGTH, 0); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); ReferenceCountUtil.release(request); }
Front-end JavaScript code:
var socket = new WebSocket("ws://127.0.0.1:18080/ws?token=xxxx");
Although the server returns 401 and closes the connection, the browser does not respond in any way.
Solution
The browser is unresponsive because the 401 response is ignored during the WebSocket handshake phase. We need to process it during the handshake phase or after the connection is established.
Solution 1: Return 401 response during the handshake phase
In the WebSocket handshake phase (HTTP request phase), if token verification fails, the HTTP 401 response will be directly returned to avoid establishing a WebSocket connection. Modify the server-side code:
if (!validateToken(request)) { FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.UNAUTHORIZED); response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=utf-8"); response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes()); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); return; }
Solution 2: Send custom messages after the connection is established
If you need to process 401 after the WebSocket connection is established, you can send a custom message to notify the front end immediately after the connection is established. Add a custom processor in Netty's WebSocketServerProtocolHandler
:
channel.pipeline().addLast(new WebSocketServerProtocolHandler("/ws") { @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt == WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE) { if (!validateToken()) { ctx.writeAndFlush(new TextWebSocketFrame("401 Unauthorized")).addListener(ChannelFutureListener.CLOSE); } } super.userEventTriggered(ctx, evt); } });
Front-end JavaScript code needs to listen for onmessage
events:
socket.onmessage = function(event) { if (event.data === "401 Unauthorized") { console.log("Connection closed, reason: 401 Unauthorized"); socket.close(); } };
Through the above method, the browser can correctly process the 401 status code, and the front-end can also receive corresponding feedback information, thereby solving the problem of the browser's unresponsiveness. Which solution to choose depends on the specific application scenario and requirements.
The above is the detailed content of What is the reason why the browser does not respond after the WebSocket server returns 401? How to solve it?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Exchanges that support cross-chain transactions: 1. Binance, 2. Uniswap, 3. SushiSwap, 4. Curve Finance, 5. Thorchain, 6. 1inch Exchange, 7. DLN Trade, these platforms support multi-chain asset transactions through various technologies.

Aavenomics is a proposal to modify the AAVE protocol token and introduce token repos, which has implemented a quorum for AAVEDAO. Marc Zeller, founder of the AAVE Project Chain (ACI), announced this on X, noting that it marks a new era for the agreement. Marc Zeller, founder of the AAVE Chain Initiative (ACI), announced on X that the Aavenomics proposal includes modifying the AAVE protocol token and introducing token repos, has achieved a quorum for AAVEDAO. According to Zeller, this marks a new era for the agreement. AaveDao members voted overwhelmingly to support the proposal, which was 100 per week on Wednesday

Suggestions for choosing a cryptocurrency exchange: 1. For liquidity requirements, priority is Binance, Gate.io or OKX, because of its order depth and strong volatility resistance. 2. Compliance and security, Coinbase, Kraken and Gemini have strict regulatory endorsement. 3. Innovative functions, KuCoin's soft staking and Bybit's derivative design are suitable for advanced users.

The platforms that have outstanding performance in leveraged trading, security and user experience in 2025 are: 1. OKX, suitable for high-frequency traders, providing up to 100 times leverage; 2. Binance, suitable for multi-currency traders around the world, providing 125 times high leverage; 3. Gate.io, suitable for professional derivatives players, providing 100 times leverage; 4. Bitget, suitable for novices and social traders, providing up to 100 times leverage; 5. Kraken, suitable for steady investors, providing 5 times leverage; 6. Bybit, suitable for altcoin explorers, providing 20 times leverage; 7. KuCoin, suitable for low-cost traders, providing 10 times leverage; 8. Bitfinex, suitable for senior play

Cryptocurrency data platforms suitable for beginners include CoinMarketCap and non-small trumpet. 1. CoinMarketCap provides global real-time price, market value, and trading volume rankings for novice and basic analysis needs. 2. The non-small quotation provides a Chinese-friendly interface, suitable for Chinese users to quickly screen low-risk potential projects.

The core advantage of gate.io (global version) is that the interface is minimalist, supports Chinese, and the fiat currency trading process is intuitive; Binance (simplified version) has the highest global trading volume, and the simple version model only retains spot trading; OKX (Hong Kong version) has the simple version of the interface is simple, supports Cantonese/Mandarin, and has a low threshold for derivative trading; Huobi Global Station (Hong Kong version) has the core advantage of being an old exchange, launches a meta-universe trading terminal; KuCoin (Chinese Community Edition) has the core advantage of supporting 800 currencies, and the interface adopts WeChat interaction; Kraken (Hong Kong version) has the core advantage of being an old American exchange, holding a Hong Kong SVF license, and the interface is simple; HashKey Exchange (Hong Kong licensed) has the core advantage of being a well-known licensed exchange in Hong Kong, supporting France

Can. The two exchanges can transfer coins to each other as long as they support the same currency and network. The steps include: 1. Obtain the collection address, 2. Initiate a withdrawal request, 3. Wait for confirmation. Notes: 1. Select the correct transfer network, 2. Check the address carefully, 3. Understand the handling fee, 4. Pay attention to the account time, 5. Confirm that the exchange supports this currency, 6. Pay attention to the minimum withdrawal amount.

The steps to draw a Bitcoin structure analysis chart include: 1. Determine the purpose and audience of the drawing, 2. Select the right tool, 3. Design the framework and fill in the core components, 4. Refer to the existing template. Complete steps ensure that the chart is accurate and easy to understand.
