Hello everyone, I'm Xiao Cai~
This article mainly introduces the use of
websocket
The WeChat public account has been opened, , students who didn't follow it remember to pay attention!
As a prospective freshman, a small vegetable farmer found an internship early, and he was not so comfortable with everything when he first arrived at the company. Cheng Li, as a mentor, arranged a requirement for the small vegetable farmer this day, and wanted to realize a simple "manual customer service". "Demand, that is, instant messaging. Although the small vegetable farmer had little experience, he readily took over the demand in order to leave a good impression on the instructor.
After receiving the demand, the small vegetable farmer began to think about how to realize instant messaging. He began to check the cases of online customer service on major platforms~
He summed up the requirements: online customer service, the requirements are very simple to understand, it is equivalent to a web chat page, that is, the client can instantly pull the response from the server, although WeChat is usually heavily used, but when it comes to its own implementation, it is I am confused, seeing that the morning is about to pass, but I have not made any progress. The only progress is to find the above picture, but it is useless~
After eating at noon, everyone else had taken their breath away, and the small vegetable farmer was still worrying about this demand in front of the computer. Get the response through the interface! The wonderful idea of catching news with the entire timing task at the front end directly impacts the brains of vegetable farmers
"Wonderful", the small vegetable farmer began to talk about his good idea, and the troubles came and went quickly~ I couldn't help but think about it and started to write the code.
is as follows:
Server:
Client:
setInterval(function () {
$.ajax({
async: false,
url: "localhost:8080/roll",
type: "get",
success(data){
console.log("success");
}
})
},1000)
After writing it, Xiaocai Nong simply verified it and found that all the functions were satisfied, so he started to showcase to the instructor Cheng Li. Cheng Li simply went through the page effect, feeling that the effect was within expectations, and asked Xiaocai Nong to submit the code to prepare for combined release. span
After the small vegetable farmer submitted the code, he couldn't help but feel very happy, and he felt very good about himself. He was able to complete this not-so-simple requirement within the specified time. But before the small vegetable farmer was happy for too long, the tutor's ding-ding prompt flashed on the computer, "Little vegetable farmer, are you free now? Come here." A bad idea came to the mind of the small vegetable farmer, "This shouldn't be a bug." Xiaocai Nong came to the instructor's workstation tremblingly, "I just reviewed your code", not been released yet, so it is not a bug, fortunately~ Xiaocai Nong thought to himself. "I took a look at the way you implemented this function. Although this method can meet the requirements, it is not a good solution", the instructor continued. "Through the polling method, although the chat data can be obtained from the server, the frequent request defects of the interface will also be obvious, which wastes bandwidth and traffic, and the pressure on the server will be relatively large, so this method is not very good. The solution, you can go back and think about whether there are any other better solutions!"
"Yeah, I didn't think about it, then I'll go back and change it!" The small vegetable farmer was not deep in the world, and the instructor said so, so this plan must be passed, and he quickly connected.
After returning to the workplace, the small vegetable farmer was inevitably a little frustrated. He wanted to perform well, but he did not expect that the plan he came up with had so many drawbacks. It's been a while, and I don't have time to think about it now. How to achieve it is the most important thing! The small vegetable farmer fell into contemplation again, how can this be done~
The small vegetable farmer then opened a certain degree and saw a keyword SSE
The full name of SSE is Server-Sent Events, which refers to the automatic acquisition of updates from the server by the web page, that is, the automatic acquisition of the data pushed by the server to the web page. This is an H5 attribute. Except for IE, other standard browsers are basically compatible.
The small vegetable farmer studied it carefully and found that this method is somewhat similar to his previous implementation, but it does not require the client to obtain it regularly. Instead, the server declares to the client that it wants to send stream information, and then sends it continuously. At this time, the client will not close the connection, and will always wait for a new data stream sent by the server. "Wonderful, this way you won't be setting up connections frequently and wasting bandwidth." The small vegetable farmer was excited again. This time, he will definitely be able to meet the needs of the instructor! The small vegetable farmer spent another afternoon refactoring the code implementation and submitted it~
pseudocode
Server:
Client:
Don't be surprised this time! The small vegetable farmer thought silently in his heart, but the good times did not last long, and Ding Ding began to flicker again, this and this. . . The mentality of the small vegetable farmer has collapsed a little. It's over. This time the trial period may end early.
Heavy is not enough to describe the current state of the small vegetable farmer, "I just saw that your implementation method is much improved than before, but we should have a better implementation method, you may consider using websocket to achieve it, Don't worry, we can go back and have a good look." The small vegetable farmer didn't hear the blame in his imagination, and couldn't help feeling warm in his heart, Websocket! This time I have to understand it clearly and then implement it, but I can't think of it as before. I started to study at the station.
Websocket
This time, the small vegetable farmer decided not to go online in order to shorten the working hours. He opened the search engine and started looking for relevant information about "Websocket".
What is websocket?
WebSocket is a TCP-based network protocol, and it is also a duplex communication , which allows both the client to send messages to the server, and the server to actively send messages to the client. In WebSocket, the browser and the server only need to complete a handshake, and a persistent connection can be established between the two for two-way data transmission.
In the WebSocket API, the browser and the server only need to do a handshake, and then a fast channel is formed between the browser and the server. Data can be transferred directly between the two.
"Good guy, this introduction directly sums up my needs! Seconds~", the small vegetable farmer was overjoyed, the sky was so blue~ He couldn't wait to look down
What are the features of WebSocket?
1. Support two-way communication, more real-time
2. The protocol identifier is ws. If you use Https-like encryption, you need to use wss
3. Lightweight, low performance overhead, and very efficient communication
4. Based on the IQ of the TCP protocol, the implementation of the server is relatively easy
It turned out to be the case, the small vegetable farmer began to analyze the drawbacks of his first two implementation methods
1. timed polling method
The advantage is that the implementation is simple, and thinking of this small vegetable farmer blushed. The disadvantage is also what the instructor said, there is a certain delay, and the pressure on the server is large, wasting bandwidth traffic, because most of the requests are invalid
2. SSE mode
This method is somewhat similar to websocket, but it can only communicate in simplex. After the connection is established, it can only be sent from the server to the client, and one connection is occupied. If the client needs to communicate with the server, an additional connection needs to be opened.
The server written in java comes with a websocket package, which is written as follows:
It is also very simple for the client to implement websocket, only the following API is required
var Socket = new WebSocket(url, [protocol] );
The first parameter, url, specifies the connection URL. The second parameter protocol is optional and specifies acceptable subprotocols
There are 4 kinds of events in websocket as follows:
event | event handler | describe |
---|---|---|
open | Socket.onopen | Triggered when a connection is established |
message | Socket.onmessage | Triggered when the client receives data from the server |
error | Socket.onerror | Triggered when a communication error occurs |
close | Socket.onclose | Fired when the connection is closed |
code show as below:
At this point, websocket communication has been realized. When the small vegetable farmer was just about to submit, an idea arose. websocket is the suggestion given to me by the instructor. Although I have already completed it, will there be a better way? Let the teacher shine? Thinking of this, the small vegetable farmer could not help but grind his fists. After some searching, he did not expect to find it.
STOMP protocol~ This should be what I want~
What is the STOMP protocol?
STOMP (Simple Text-Orientated Messaging Protocaol) is a simple text-oriented messaging protocol that provides an interoperable connection format that allows STOMP clients to interact with any STOMP message broker Broker. The design is simple and easy to use develop
What are the characteristics of STOMP?
1. STOMP is a frame-based protocol, and its frame is modeled after HTTP
2. The STOMP framework consists of a command, an optional set of headers, and an optional body
3. STOMP is based on text, but also allows the transmission of binary messages
This is a bit of a , a heart-wrenching sigh~
What is STOMP frame?
The structure of STOMP is as follows:
COMMAND header1:value1 header2:value2 Body^@
Send and receive use the commands
SEND
andSUBSCRIBE
, and can also usedestination
to describe the content and recipient of the message
What are the common frames of STOMP?
- connection related
1. CONNECT
2. CONNECTED (successful connection)
- Client related
1. SEND (send)
2. SUBSRIBE
3. UNSUBSCRIBE
4. BEGIN
5. COMMIT (commit)
6. ABORT (interrupt)
7. ACK (confirmation)
8. NACK (denial)
9. DISCONNECT (disconnect)
- Server related
1. MESSAGE
2. RECEIPT (receive)
3. ERROR
The small vegetable farmer cluttered his notes about STOMP, so why does have websocket, and stomp is needed, what benefits does the appearance of stomp bring, or what problems does it solve? . The small vegetable farmer gradually began to learn to think. He began to check the relevant information of stomp again. After a lot of tossing, he finally found some answers: the creation of WebSocket is very similar to the use of TCP socket transmission, and the transmitted message is undefined , that is, the degree of freedom is very high, and there is no clear agreement, then a high-level application protocol may be needed to define the semantic format of these messages at this time, that is to say, STOMP is also a protocol, a sub-type of WebSocket. A protocol that guarantees that both ends of the connection follow these semantics.
So what are the benefits of using STOMP
1. STOMP has defined the semantic format, we can do it without customization
2. Ready-made stomp.js client, out of the box
3. You can use the supporting message broker for broadcasting, which is suitable for multi-cluster situations (RabbitMQ, ActiveMQ)
Knowing that if you don't write the code here, you are really paddling. The small vegetable farmer opened the project and started to write the code~
To use stomp, you need to define the configuration class of stomp first
The above ws
is the url of the front end, the back end declares the endpoint, and the front end connects.
stomp interceptor:
Where to receive client messages:
send messages:
The code of the server part has been implemented here~ the client part is also very simple, only need to introduce two js to achieve
Here, in order to receive messages on the client side, you must first subscribe to a destination destination
, that is, use subscribe()
to subscribe. This method has two required parameters: destination , callback function . There is also an optional parameter headers .
When the client is successfully connected to the server, it can call send()
to send the STOMP message. This method must have a parameter that describes the corresponding STOMP destination. In addition there can be two optional parameters: headers
, object
type contains additional information header
At this point, the function of stomp has been realized, and the small vegetable farmer quickly opened the page to verify the results:
At this point, Xiaocai Nong has realized the function of online customer service~ Although Xiaocai Nong has realized the function of chat room, it also encountered many difficulties in the process of realization, so I have to record it quickly!
You can see that some keywords are involved above:
- Message : message, carrying header and payload
- MessageHandler : The entity that handles client messages
MessageChannel : Entities that decouple message senders and message receivers
- clientInboudChannel : Used to receive messages from WebSocket clients
- clientOutboundChannel : Used to send server messages to WebSocket clients
- brokerChannel : used to send messages from server, application to message broker
- Broker : middleware that stores messages, clients can subscribe to messages in the broker
It can be seen that stomp is a similar subscription publishing model. We can dynamically and flexibly declare the topic. The front end can subscribe to different topics and receive messages under different topics. Friends who have been in contact with message queues will definitely not be unfamiliar~
The small vegetable farmer has completed the needs of "manual customer service". He can't help laughing when he thinks of all kinds of irritable behaviors because he has no thoughts before. Therefore, he said that he should not be impatient when he does not know how to do it. If there is any problem, he should deal with it in time. Clear thinking, you can ask more, but you can't not learn~
Don't talk empty-handed, don't be lazy, and be a with Xiaocai bragging about X to do the architecture~ Just follow and be a companion, so that Xiaocai is no longer alone. See you below!
If you work harder today, tomorrow you will be able to say one less thing to ask for help!
I am Xiao Cai, a man who grows stronger with you.
💋
The WeChat public account has been opened, , students who didn't follow it remember to pay attention!
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。