


What is the reason why the browser does not respond after the WebSocket server returns 401? How to solve it?
Apr 19, 2025 pm 02:21 PMNetty 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

Undress AI Tool
Undress images for free

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

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

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

Against the backdrop of violent fluctuations in the cryptocurrency market, investors' demand for asset preservation is becoming increasingly prominent. This article aims to answer how to effectively hedge risks in the turbulent currency circle. It will introduce in detail the concept of stablecoin, a core hedge tool, and provide a list of TOP3 stablecoins by analyzing the current highly recognized options in the market. The article will explain how to select and use these stablecoins according to their own needs, so as to better manage risks in an uncertain market environment.

The Virtual Currency Exchange APP is a professional digital asset trading application, providing users with safe and convenient digital currency trading services. The new v6.129.0 version has upgraded the performance and operation experience, aiming to bring a smoother trading experience.

This article will discuss the world's mainstream stablecoins and analyze which stablecoins have the risk aversion attribute of "gold substitute" in the market downward cycle (bear market). We will explain how to judge and choose a relatively stable value storage tool in a bear market by comparing the market value, endorsement mechanism, transparency, and comprehensively combining common views on the Internet, and explain this analysis process.

As the market conditions pick up, more and more smart investors have begun to quietly increase their positions in the currency circle. Many people are wondering what makes them take decisively when most people wait and see? This article will analyze current trends through on-chain data to help readers understand the logic of smart funds, so as to better grasp the next round of potential wealth growth opportunities.

The latest official version of the virtual currency trading platform v6.129.0 is a professional and secure digital asset trading application created for Android users. It provides rich market conditions, convenient trading functions and multiple security protection, and is committed to providing users with a first-class trading experience.

Airdrops in the cryptocurrency field are a marketing promotion method for the project to distribute a certain number of tokens for free to community members or potential users. In this way, the project party hopes to increase the visibility of the tokens and attract more users to participate in the project, thereby expanding the size of the community and increasing the liquidity of the tokens. For users, airdrops provide opportunities to obtain project tokens without initial investment, and are one of the ways to get in touch with and understand new projects in the early stage.

This article will introduce several mainstream stablecoins and explain in depth how to evaluate the security of a stablecoin from multiple dimensions such as transparency and compliance, so as to help you understand which stablecoins are generally considered relatively reliable choices in the market, and learn how to judge their "hazard-haven" attributes on your own.

Recently, Bitcoin hit a new high, Dogecoin ushered in a strong rebound and the market was hot. Next, we will analyze the market drivers and technical aspects to determine whether Ethereum still has opportunities to follow the rise.
