Implementation of Java websocket and sample code of spring websocket

Start learning websocket, and prepare to use it to realize a log that outputs log4j in real time on the page and the log of the console.

First, you should know some basic information:

1. Java 7 began to support websocket, which was only defined but not implemented

2. Tomcat7 and above, jetty 9.1 and above have implemented websocket, and other containers have not been studied

3. Spring 4.0 and above have added websocket support

4. Spring supports websocket communication of stomp protocol

5. Websocket, as an extension of Java, belongs to the javax package directory and usually needs to be imported manually. Taking Tomcat as an example, websocket API can be found in the Tomcat / lib directory jar

Start implementation

First, write an ordinary websocket client and directly introduce the jars under the Tomcat directory. The main jars are: websocket API jar、tomcat7-websocket. jar

The URL format must start with WS, followed by the registered websocket address

Client. Java is used to send and receive messages

At this step, the sending and receiving of messages on the client has been completed. Now start writing the server code with spring 4.0, where POM If the XML is too long, it will not be posted. Jackson, spring websocket and spring message will be used

In this way, an ordinary websocket is completed, and you can also integrate security control and so on

Spring also supports an annotation method, which can realize subscription and broadcasting. It adopts stomp format protocol, similar to MQ. In fact, it should use MQ message format. The following is the implementation

Same client:

It must be noted here that the line feed and end symbols are the symbols specified in the stomp protocol. If they are wrong, they cannot be parsed

Server configuration

It's all done here.

template. Convertandsend ("/ topic / greetings", "notification")// This means broadcasting to / topic / meetings subscribers

When connecting with socktjs, there will be a request to access the / Info address

If you receive and send messages on a browser connection, use Sockt JS and stomp js

In the browser, you can see that the request returns the 101 status code, which means switching the protocol

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>