Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the principle of WebSocket and the implementation of Tomcat

2025-01-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

WebSocket principle and the realization of Tomcat is how, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain in detail for you, people with this need can come to learn, I hope you can gain something.

Nowadays, active push messages from server to client need to be implemented in many scenarios. For the traditional HTTP, we all know that it must be through an active request, each Request corresponds to a Response, at this time to achieve server push, there must be an active request.

To this end, people have come up with a series of ways, such as ajax long polling, long connection and so on, but compared with the invalid requests of long polling, it is better to use the more convenient and resource-free implementation we mentioned today.

Compared with HTTP requests, you will obviously feel that for HTTP, whether asynchronous or synchronous, you can observe in the developer tool that the application sends a new request to the server and then processes and displays it according to the returned information.

On the other hand, WebSocket, after the first handshake to establish a connection, the subsequent messages do not re-establish the connection, that is, you cannot observe its subsequent requests.

This is also the difference between HTTP and WebSocket.

Inside Tomcat, let's look at how Websocket works and works.

First, take a look at how WebSocket is initialized.

Regardless of the type of request, it is processed in ApplicationFilterChain, and the flow direction of the entire processing is determined by whether or not Filter is configured. I have previously introduced the working principle and request process of Filter: the chain of responsibility mode and how Filter works. No matter which application, in fact, Tomcat will add such a Filter by default:

WsFilter

This Filter is used to handle WebSocket, but not all of it, because its filter-mapping is

/ *

FilterRegistration.Dynamic fr = servletContext.addFilter (

"Tomcat WebSocket (JSR356) Filter", new WsFilter ()

Fr.setAsyncSupported (true)

EnumSet types = EnumSet.of (DispatcherType.REQUEST, DispatcherType.FORWARD)

Fr.addMappingForUrlPatterns (types, true, "/ *")

The above code uses Servlet3.0 's newly added dynamic declaration Filter implementation to dynamically add WsFilter to the application's filter chain.

In this Filter, it is also judged at the entrance that only the WebSocket request is processed, and the rest is skipped.

/ / This filter only needs to handle WebSocket upgrade requests

If (! sc.areEndpointsRegistered ()) | |

! UpgradeUtil.isWebSocketUpgradeRequest (request, response)) {

Chain.doFilter (request, response)

Return

}

The act of adding Filter is executed when the application is started. The call stack is as follows:

At org.apache.catalina.core.StandardContext.addFilterMap (StandardContext.java:2836)

At org.apache.catalina.core.ApplicationFilterRegistration.addMappingForUrlPatterns (ApplicationFilterRegistration.java:104)

At org.apache.tomcat.websocket.server.WsServerContainer. (WsServerContainer.java:141)

At org.apache.tomcat.websocket.server.WsSci.init (WsSci.java:131)

At org.apache.tomcat.websocket.server.WsSci.onStartup (WsSci.java:47)

At org.apache.catalina.core.StandardContext.startInternal (StandardContext.java:5151)

Request connection establishment

A connection needs to be established before the data can be sent. While WebSocket is still essentially a TCP connection, although it appears to be through HTTP, it is only because its first handshake needs to be established through HTTP.

We use the echo example in the websocket sample that comes with Tomcat to illustrate how WebSocket is used and how it is implemented within Tomcat.

Examples of echo can be found at:

TOMCAT_HOME\ webapps\ examples\ websocket

The java code is located at:

TOMCAT_HOME\ webapps\ examples\ WEB-INF\ classes\ websocket\ echo

In the code, the implementation of connect and echo message is as follows:

Function connect () {

Var target = document.getElementById ('target'). Value

If (target = ='') {

Alert ('Please select server side connection implementation.')

Return

}

If ('WebSocket' in window) {

Ws = new WebSocket (target)

} else if ('MozWebSocket' in window) {

Ws = new MozWebSocket (target)

} else {

Alert ('WebSocket is not supported by this browser.')

Return

}

Ws.onopen = function () {

SetConnected (true)

Log ('Info: WebSocket connection opened.')

}

Ws.onmessage = function (event) {

Log ('Received:' + event.data)

}

Ws.onclose = function (event) {

SetConnected (false)

Log ('Info: WebSocket connection closed, Code:' + event.code + (event.reason = "?": ", Reason:" + event.reason))

}

}

We see that the entire websocket object handles three events:

Connect

Message

Close

On the other hand, the message is sent directly using the send method of websocket.

During the first connection handshake, we can observe through the developer tools:

The protocol is switched through Upgrade and connected to the Server of WebSocket.

At this time, the Upgrade is carried out through the Filter we mentioned earlier.

In Filter, subsequent calls to the WebSocket specification are implemented through the doUpgrade method of UgradeUtil.

As for the support of WebSocket Server, we can see from the example of Echo that it can be done either directly using the class of Endpoint or through annotated equations.

For example, the following code declares an Endpoint of Websocket in the form of annotations

@ ServerEndpoint ("/ websocket/echoAnnotation") public class EchoAnnotation {

@ OnMessage

Public void echoTextMessage (Session session, String msg, boolean last) {

Try {

If (session.isOpen ()) {

Session.getBasicRemote () .sendText (msg last)

}

} catch (IOException e) {

}

}

According to the annotation, a PojoServer is generated inside the Tomcat and the method currently labeled @ OnMessage is called using reflection.

As for the distribution of the request, when we introduced Connector earlier, we briefly said that it was through

Endpoint-> Handler-> Protocol

(Connector component of Tomcat)

Different requests are forwarded differently in Protocol

} else if (processor.isAsync ()) | |

State = = SocketState.ASYNC_END) {

State = processor.asyncDispatch (status)

} else if (processor.isComet ()) {

State = processor.event (status)

} else if (processor.isUpgrade ()) {

State = processor.upgradeDispatch (status)

} else if (status = = SocketStatus.OPEN_WRITE) {

/ / Extra write event likely after async, ignore

State = SocketState.LONG

}

After the connection is established, the subsequent data transmission can no longer be observed through the developer tool, which is the main reason why WebSocket can implement server push. In essence, after the connection is established, it is no longer a HTTP request, but a TCP connection.

And because of the specification implementation of WebSocket in HTML5 and the support of various mainstream browsers, most application servers have been supported according to the specification. Many scenarios that want to implement server push can also be considered using WebSocket.

Open the webSocket sample of Tomcat and try it!

Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report