当前位置:网站首页>Websocket in the promotion of vegetable farmers

Websocket in the promotion of vegetable farmers

2022-06-25 05:47:00 Cai Bucai

Hello, everyone , I'm a small dish ~

This paper mainly introduces websocket Use

The official account of WeChat has been opened , A small dish is a good memory , If you don't pay attention to it, remember to pay attention to it !

As a prospective fresh vegetable farmer, he found an internship early , When I first arrived at the company, everything didn't adapt so well , Cheng Li, as a tutor, arranged a demand for small vegetable farmers this day , Want to implement a simple 《 Manual customer service 》 demand , Instant messaging . Small vegetable farmers, although they have little experience , But in order to leave a good impression on the tutor, he took over the demand at once .

After taking over the demand, small vegetable farmers began to think about how to realize instant messaging , He began to check cases about online customer service on major platforms ~

image-20220204143551034

He summed up the needs : Online Service , Requirements are easy to understand , It's equivalent to a web The chat page of , That is, the client can immediately pull the response from the server , Although wechat is heavily used at ordinary times , But when it comes to their own realization, they are full of fog , Seeing that the morning is about to pass , I haven't made any progress , The only progress is to find the above picture , But it's no use ~

After lunch , Everyone else has rested , And small vegetable farmers are still worried about this demand in front of the computer , I can't help feeling a little irritable , I began to miss my days at school . Get the response through the interface ! The whole timing task of the front-end goes to get messages This wonderful idea directly hit the vegetable farmer's brain

" Wonderful ", Small vegetable farmers began to talk about their good ideas with relish , Troubles come and go quickly ~ I couldn't help thinking about it and began to write code , That's a flow of clouds and water

The pseudocode is as follows

Server side :

client :

setInterval(function () {
    $.ajax({
        async: false,
        url: "localhost:8080/roll",
        type: "get",
       
        success(data){
         console.log("success");
        }
    })
},1000)

After finish , The vegetable farmer simply verified , When he found that all the functions had been met, he began to ask his mentor Cheng Li showcase 了 , Cheng Li simply went through the page effect , I feel that the effect is expected, so I let the vegetable farmers submit the code for merger and release

After submitting the code, the vegetable farmer couldn't help but rejoice , I feel very good about myself , It's not so simple to complete this requirement within the specified time , It must be further away from your regular job ! But I didn't wait too long for the vegetable farmers to be happy , The teacher's tinkling prompt flashed on the computer ," Vegetable farmers , Do you have a minute , Come here ". Bad thoughts floated on the minds of small vegetable farmers ," This shouldn't happen bug Is that right ". The vegetable farmer came to the tutor's station trembling ," I just review Check your code ", It hasn't been released yet , That is not bug It's something , Fortunately ~ The vegetable farmer thought to himself ." I looked at the implementation of your function , Although this way can meet the needs , But it's not a good solution ", The tutor continued .“ By polling , Although you can get chat data from the server , However, the frequent request defect of the interface will also be obvious , It's a waste of bandwidth and traffic , The pressure on the server will be greater , So this way is not a good solution , You can go back and see if there are any other better solutions !”

" Mm-hmm , I didn't think about it , Then I'll go back and change it !" Small vegetable farmers are not deeply involved in the world , That's what the tutor said , Then this plan must pass, Quickly pick up .

When the vegetable farmer returns to the station , Inevitably a little depressed , I wanted to do well , I didn't expect that the plan I came up with had so many disadvantages . A big head , I don't have time to think about it now , How to realize it is the most important thing ! The vegetable farmer was lost in thought again , What should I do ~

The vegetable farmer then opened a certain degree , See a keyword SSE

SSE Full name Server-Sent Events, Refers to the web page automatically get updates from the server , That is to automatically obtain the data pushed by the server to the web page , This is a H5 Properties of , except IE, Other standard browsers are basically compatible

The vegetable farmer carefully studied , I found that this method is somewhat similar to my previous implementation , But you don't need the client to get it regularly , Instead, the server declares to the client that it wants to send stream information , Then send it continuously . At this time, the client will not close the connection , I will be waiting for the new data stream from this server ." Wonderful , In this way, connections will not be established frequently , Waste bandwidth ", The vegetable farmer is excited again , This time, I'm sure I can meet the needs of my tutor ! The vegetable farmer spent another afternoon refactoring the code implementation , And submitted ~

Pseudo code

Server side :

client :

Don't have another accident this time ! Small vegetable farmers meditate in their hearts , But not for long , Ding Ding starts flashing again , This is this. ... The mentality of small vegetable farmers has collapsed , Finished , This probationary period may end in advance .

Heavy is not enough to describe the current state of small vegetable farmers ," I just looked at your implementation, which is much better than before , But we should have a better implementation , Might as well consider using websocket To achieve , It's okay, don't worry , We can go back and have a good look ". The vegetable farmer did not hear the imagined blame , I can't help but feel warm in my heart ,Websocket! This time I need to understand clearly before I start to realize , You can't do it for speed as before After making up your mind , The vegetable farmer returned to the station and began to study Websocket

This time, the vegetable farmers decided not to go online hastily in order to shorten the working hours , He turned on the search engine and started looking for information about 《Websocket》 Relevant information about .

What is? websocket?

WebSocket It's based on TCP Network protocol , At the same time, he is also a kind of Full duplex communication protocol , It allows the client to send messages to the server , It also allows the server to actively send messages to the client . stay WebSocket in , The browser and the server only need to complete a handshake , A persistent connection can be established between the two , Two way data transfer

stay WebSocket API in , All browsers and servers need to do is shake hands , then , This creates a fast channel between the browser and the server . Data can be transmitted directly between the two .

" good heavens , This profile directly summarizes my needs ! Second. ~", The vegetable farmer was overjoyed , The sky is so blue ~ He couldn't wait to look down

WebSocket What are the characteristics of ?

1、 Support two-way communication , More real time

2、 The protocol identifier is ws , If you use something like Https The encryption method needs to use wss

3、 Lightweight , Low performance overhead , Communication is very efficient

4、 Based on the TCP Agreement IQ , The server-side implementation is relatively easy

It turns out that's the same thing , Small vegetable farmers began to analyze the disadvantages of their first two implementation methods

1、 The way of regular polling

The advantage is that it's easy to implement , Think of this little vegetable farmer's old face. . Shortcomings are also what the tutor said , There is a certain delay , And the pressure on the server is high , Waste bandwidth traffic , Because most requests are invalid

2、SSE The way

This way and websocket Some similar , But it can only simplex communication , Once the connection is established , It can only be sent from the server to the client , And occupy a connection , If the client needs to communicate with the server , An additional connection needs to be opened

adopt java The prepared server comes with websocket package , Write as follows :

Client implementation websocket It's very simple , Just the following API

var Socket = new WebSocket(url, [protocol] );
The first parameter url, Specify connected URL. The second parameter protocol It's optional , Specifies an acceptable subprotocol

stay websocket There is 4 The events are as follows :

event Event handler describe
openSocket.onopen Triggered when connection is established
messageSocket.onmessage Triggered when client receives server data
errorSocket.onerror Triggered when a communication error occurs
closeSocket.onclose Triggered when the connection is closed

The code is as follows :

Come here ,websocket Communication has been realized , When the vegetable farmer was just about to submit , An idea arose ,websocket It's my tutor's advice , Although I have finished , But is there a better way , It can brighten the teacher's eyes ? Think of it here. , Small vegetable farmers can't help rubbing their hands and fists . Find out , I didn't expect him to find it ,STOMP agreement ~ This should be what I want ~

What is? STOMP agreement ?

STOMP (Simple Text-Orientated Messaging Protocaol) , It is a simple text oriented messaging protocol , Provides an interoperable connection format , allow STOMP The client sends data to any server STOMP The message broker Broker Interact , Design simple , Easy to develop

STOMP Characteristics ?

1、STOMP It's a frame based protocol , Its frame In order to HTTP For the model

2、STOMP The framework consists of commands , A set of optional headers and optional bodies make up

3、STOMP Based on text , But binary messages are also allowed to be transmitted

It's a little cow , A wandering sigh ~

STOMP What is the frame ?

STOMP The structure is as follows :

COMMAND
header1:value1
header2:value2

Body^@

Send and receive commands separately SEND and SUBSCRIBE, And you can use destination To describe the content of the message and the recipient

STOMP What are the commonly used frames ?

  • Connection correlation

1、CONNECT ( Connect )

2、CONNECTED ( Successfully connected )

  • Client related

1、SEND( send out )

2、SUBSRIBE( subscribe )

3、UNSUBSCRIBE( Unsubscribe )

4、BEGIN( Start )

5、COMMIT( Submit )

6、ABORT( interrupt )

7、ACK( confirm )

8、NACK( Deny )

9、DISCONNECT( disconnect )

  • Server related

1、MESSAGE( news )

2、RECEIPT( receive )

3、ERROR( error )

The vegetable farmer sorted out the information about STOMP The notes , that Why websocket, There needs to be stomp,stomp What are the benefits of the emergence of , Or what problem has been solved ?. Vegetable farmers are gradually learning to think , He started checking again stomp Related information , After some tossing , Finally found some answers :WebSocket The creation of , It's very similar to using TCP Socket transfer , The transmitted message is undefined , That is, the degree of freedom is very high , There is no clear agreement , At this time, a high-level application protocol may be needed to define the semantic format of these messages , in other words STOMP It's also an agreement , An act WebSocket Sub agreement of , It can ensure that both ends of the connection follow these semantics .

So use STOMP What are the benefits

1、STOMP The semantic format has been defined , We don't need to customize

2、 Ready made stomp.js client , Open the box

3、 You can use a supporting message broker to broadcast , Suitable for multi cluster situations (RabbitMQ、ActiveMQ)

It's learned that if you don't move the handwritten code here, you're really rowing , The vegetable farmer opened the project and began to roll out the code ~

To use stomp, You need to define stomp Configuration class

image-20220219224218722

above ws It's the front end url, The backend declares the endpoint , Connect the front end .

stomp Interceptor :

Where client messages are received :

Send a message :

Here, the code of the server has been implemented ~ The client part is also very simple. You only need to introduce two js And then

Here, in order to receive the message at the client , You must subscribe to a destination first destination, That is to use subscribe() To subscribe , This method has two required parameters : Destination , Callback function . There is also an optional parameter headers.

When the connection between the client and the server is successful , You can call send() To send the STOMP news . This method must have a parameter , Used to describe the corresponding STOMP Destination . In addition, there can be two optional parameters :headers,object Type contains additional information headers

It has been realized here stomp The function of , The vegetable farmer quickly opened the page to verify the results :

image-20220219221718490

​ Come here , Small vegetable farmers have realized the function of online customer service ~ Although small vegetable farmers realize the function of chat room , But there are also many difficulties in the process of implementation , You have to record it quickly !

You can see that the above involves some keywords :

  • Message: news , carry header and payload
  • MessageHandler: Handle client The entity of the message
  • MessageChannel: Decouple the entities of message sender and message receiver

    • clientInboudChannel: For from WebSocket The client receives messages
    • clientOutboundChannel: Used to send server messages to WebSocket client
    • brokerChannel: Used to retrieve data from the server , Send messages to the message broker in the application
  • Broker: Middleware for storing messages ,client You can subscribe to broker The messages in the

It can be seen that stomp Is a similar subscription publishing mode , We can declare dynamically and flexibly The theme , The front end can subscribe to different topics , Received messages under different topics , Friends who have been in contact with the message queue will certainly not be unfamiliar ~

The vegetable farmer has finished here 《 Manual customer service 》 The needs of , Thinking of all kinds of irritable behaviors before you because you have no thoughts, you can't help laughing awkwardly , So don't be impatient when you meet someone you don't know , If you have problems, you should clarify your ideas in time , You can ask more , But I have to learn ~

Don't talk , Don't be lazy , Make one with the side dish Blowing cattle X Architecture It's the ape ~ Pay attention and be a companion , Let's not be alone . I'll see you later !

Try harder today , Tomorrow, you will be able to say less of a word to ask for help !

I'm a small dish , A man who grows stronger with you .

The official account of WeChat has been opened , A small dish is a good memory , If you don't pay attention to it, remember to pay attention to it !

原网站

版权声明
本文为[Cai Bucai]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202201651175240.html