Hello, everyone, I am small dish ~
This article mainly introduces the use of Websocket
Wechat public number has been opened, xiao CAI Liang, did not pay attention to the students remember to pay attention to oh!
As a prospective fresh students of small vegetable farmers early found an internship, the company is not so adapted to everything, as a mentor cheng Li this day to small vegetable farmers arranged a demand, want to achieve a simple “artificial customer service” demand, that is, instant communication. Although inexperienced, the small vegetable farmer readily accepted the demand to impress the tutor.
After receiving the demand, the small vegetable farmer began to think about how to achieve instant communication. He began to view cases about online customer service on various platforms ~
He summed up the requirements: Understand online customer service, demand is very simple, chat is equivalent to a web page, which is the client to pull to the response from the server, although WeChat heavy use at ordinary times, but in their implementation, academia at morning time is past, is no progress, the only progress is found above the picture, But there is no egg use
After lunch, other people have rested, and the small vegetable farmers are still in front of the computer for this demand and trouble, not by some fidgeting up, began to miss the school days. Get the response through the interface! The whole idea of a timed task to get the news directly hits the vegetable farmer’s brain
“Wonderful”, small vegetable farmers for their own good idea began to talk with relish, trouble come quickly to also fast ~ not by much thought began to talk chi chi to write the code, that a set can be described as flowing water
The pseudocode is as follows:
Server:
Client:
setInterval(function () {
$.ajax({
async: false.url: "localhost:8080/roll".type: "get".success(data){
console.log("success"); }})},1000)
Copy the code
After writing, small vegetable farmers simple verification, found that the function has been met and began to mentor Cheng Showcase, Cheng Li simply over the page effect, feel the effect in the expected let small vegetable farmers submit code ready to merge the release
After the small vegetable farmer submitted the code, he couldn’t help but feel happy. He felt very good that he could complete this not so simple requirement within the specified time. He must be further away from his official employment. But did not wait for the small vegetable farmers happy too long, the computer will flash from the tutor ding Ding prompt, “small vegetable farmers, now free, come over.” The bad idea floated to the small vegetable farmer’s mind, “this should not bug”. “I just reviewed your code,” but it hasn’t been released yet, so it’s not a bug. Fortunately, the small farmer thought. “I took a look at the way you implemented this feature, which, while fulfilling the requirements, is not a good solution,” the tutor continued. “By polling method, although it is possible to data from the server to chat, but the frequent requests of the interface defect will obviously, is a waste of bandwidth flow, the pressure of the server will be bigger, so this way is not a good solution, you can go back to see is there any other better solution!”
“Yes, yes, I did not consider good, then I go back to change!” The small vegetable farmer has no experience in the world, the tutor said so, then this plan must pass, hurriedly added.
Small vegetable farmers back to the station, inevitably a little depressed, originally wanted to show good performance, unexpectedly came up with so many disadvantages of the scheme. I have no time to think about it now. What matters is how to achieve it! The small vegetable farmer fell into a meditation again, how can this be good ~
The small vegetable farmer then opened a certain degree and saw a keyword SSE
SSE stands for server-sent Events. It refers to the automatic acquisition of updates from the Server by a web page, that is, the automatic acquisition of data pushed by the Server to the web page. This is an H5 attribute, which is basically compatible with other standard browsers except IE
After careful study, the small vegetable farmer found that this method is somewhat similar to his previous implementation, but there is no need for the client to regularly obtain, but the server to the client to send the stream information, and then continuously send over. The client will not close the connection and will wait for a new stream from the server. This way, you won’t have to make connections too often and waste bandwidth. “The farmer was excited again, and this time he was sure to be able to meet the mentor’s needs! The small vegetable farmer spent another afternoon reconstructing the code implementation method, and then submitted ~
Pseudo code
Server:
Client:
No more accidents this time! Small vegetable farmer heart meditation, but not for long, ding Ding began flashing again, this this this… The small vegetable farmer’s state of mind some collapse, over, this probation period may end ahead of schedule.
Heavy is not enough to describe the state of small vegetable farmers now, “I just looked at your implementation method improved a lot than before, but we should have a better implementation method, might as well consider using websocket to achieve, don’t worry, we can go back and have a good look”. Small vegetable farmers did not hear the imagined blame, not by a warm heart, Websocket! This time I can understand and then start to implement, can not think of the speed before the hasty implementation of the decision, small vegetable farmers back to the station began to study the Websocket
This time the grower decided not to rush into Websocket just to cut down on hours, and he opened up a search engine to find out more about Websocket.
What is websocket?
WebSocket is a network protocol based on TCP. It is also a full-duplex communication protocol that allows the client to send messages to the server or the server to actively send messages to the client. In WebSocket, the browser and server only need to complete a handshake, they can establish a persistent connection, 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 transmitted directly between the two.
“Boy, that’s a direct summary of what I need! Second ah ~”, the small vegetable farmer is overjoyed, the sky is so blue ~ he can’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 Https encryption is used, WSS is required
3, lightweight, low performance overhead, communication is very efficient
4, established in THE TCP protocol IQ, the implementation of the server is relatively easy
So the small vegetable farmers began to analyze the disadvantages of their first two ways of implementation
1. Periodic polling
The advantage is to realize simple, think of this small vegetable farmer old face a red. The disadvantage is also what the tutor said, there is a certain amount of latency, and the server is a lot of pressure, waste bandwidth traffic, because the vast majority of requests are invalid
2. SSE mode
This mode is similar to webSocket, but it can only simplex communication. After a connection is established, it can only be sent from the server to the client, and occupies one connection. If the client needs to communicate with the server, you need to open an additional connection
The websocket package of the server written in Java is as follows:
The client implementation of WebSocket is also quite simple, requiring only the following API
var Socket = new WebSocket(url, [protocol] );
Copy the code
The first parameter, url, specifies the URL of the connection. The second parameter, protocol, is optional and specifies an acceptable subprotocol
There are four types of events in Websocket:
The event | Event handler | describe |
---|---|---|
open | Socket.onopen | Triggered when the 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 | Triggered when the connection is closed |
The code is as follows:
At this point, websocket communication has been realized, when the small vegetable farmer was just preparing to submit, an idea arose, Websocket is my mentor’s advice, although I have finished, but is there a better way, can let the mentor’s eyes shine? Think of here, small vegetable farmer not by grinding hand wipe fist. After a bit of searching, he actually found STOMP protocol. This should be what I want
What is STOMP protocol?
STOMP (Simple Text-orientated Messaging Protocaol) is a Simple text-oriented Messaging protocol that provides an interoperable connection format. Allows STOMP clients to interact with any STOMP message Broker and is simple in design and easy to develop
What are STOMP's features?
1. STOMP is a frame-based protocol whose frames are modeled after HTTP
The STOMP framework consists of commands, an optional set of headers, and an optional body
STOMP is text-based, but also allows the transfer of binary messages
That’s a bit of a cow, a heart-wrenching exclamation
What is a STOMP frame?
The structure of STOMP is as follows:
COMMAND header1:value1 header2:value2 Body^@ Copy the code
SEND and receive use the commands SEND and SUBSCRIBE, respectively, and you can also use destination to describe the content and recipient of a message
What are the common frames for STOMP?
- Connect related
1, CONNECT
2. CONNECTED (successfully CONNECTED)
- Client-side correlation
1. SEND
2. SUBSRIBE
3. UNSUBSCRIBE
4, BEGIN
5. COMMIT
6, ABORT
7. ACK (confirm)
8. NACK
9. DISCONNECT
- Server correlation
1. MESSAGE
2, RECEIPT
3, ERROR
So why websockets, why STOMP, what benefits does STOMP bring, what problems does STOMP solve? . As the small vegetable farmer began to think, he started to look at stomp information. After a lot of trouble, he finally found some answers: The creation of WebSocket is similar to TCP socket transmission. The transmitted packets are undefined, that is, they have a high degree of freedom and no specific conventions. In this case, a high-level application protocol may be required to define the semantic format of these packets. A subprotocol that acts as a WebSocket ensures that both ends of the connection follow these semantics.
So what are the benefits of using STOMP
1. STOMP has defined the semantic format so we don’t need to customize it
2. Ready-made stomp.js client, right out of the box
3, You can use the supporting message broker to broadcast, suitable for multi-cluster (RabbitMQ, ActiveMQ)
Knowing that it is really paddling if you don’t start writing code here, the small vegetable farmer opened the project and started practicing code ~
To use STOMp, you need to define stomp’s configuration classes
The ws above is the URL for the front end, the back end declares the endpoints, and the front end makes the connections.
Stomp Interceptor:
Where to receive client messages:
Send a message:
At this point, the server part of the code is already implemented. The client part is also easy to implement with the introduction of two JS
In order to receive messages on the client side, you must subscribe to a destination, using subscribe(). This method takes two required arguments: the destination and the callback function. There is also an optional argument, headers.
When the client connects to the server successfully, send() can be called to send STOMP messages. This method must have a parameter that describes the destination of the corresponding STOMP. There are also two optional parameters: headers, and the object type contains additional headers for information
Now that stomp has been implemented, the small vegetable farmer opens the page to verify the results:
To here, small vegetable farmers have realized the online customer service function ~ although small vegetable farmers have realized the chat room function, but also encountered no small difficulties in the process of realization, have to record quickly!
You can see that there are some key words involved:
- Message: a Message that carries headers and payload
- MessageHandler: Entity that processes client messages
- MessageChannel: Decouples the message sender from the message receiver
- clientInboudChannel: Used to receive messages from WebSocket clients
- clientOutboundChannel: Used to send server messages to WebSocket clients
- brokerChannel: Used to send messages from the server, application to the message broker
- Broker: Middleware that holds messages. Clients can subscribe to messages from the Broker
As you can see, STOMp is a subscription publishing model. We can dynamically and flexibly declare topics. The front-end can subscribe to different topics and receive messages under different topics
Small vegetable farmers to this will complete the “artificial customer service” needs, think of their own before because there is no feeling and all kinds of agitated behavior is not embarrassed smile, so say in their own not when do not be impatient, there is a problem or to clarify ideas in time, can ask more, but can not learn ~
Don’t talk, don’t be lazy, and xiao CAI do a blowing bull X do architecture of the program ape ~ point a concern to do a companion, let xiao CAI no longer lonely. See you later!
Today you work harder, tomorrow you will be able to say less words!
I am xiao CAI, a man who grows stronger with you. 💋
Wechat public number has been opened, xiao CAI Liang, did not pay attention to the students remember to pay attention to oh!