当前位置:网站首页>Instant messaging websocket
Instant messaging websocket
2022-07-23 12:46:00 【Monster in the North Sea】
Business scenarios and requirements of instant messaging
Instant messaging (Instant Messaging, abbreviation IM) It allows two or more people to use the network to transmit text messages in real time 、 file 、 Voice and video communication . Instant messaging technology is applied to business scenarios that require real-time messaging .
for example : Tiktok , live broadcast , social contact App, Yellow car app
Short connection
Every time the client and server communicate , Just one connection , Disconnect when communication is over .
HTTP It's a simple request - Response protocol , It usually runs on TCP above .HTTP/1.0 The use of TCP The default is short connection .
HTTP It's a simple request - Response protocol , It usually runs on TCP above .HTTP/1.0 The use of TCP The default is short connection .HTTP It's an agreement , 1.0 The bottom layer uses short links
A long connection
It means that data can be sent continuously many times after the connection is established , Until both sides disconnect .
HTTP from 1.1 Since version , At the bottom TCP Long connection used .
Using long connected HTTP agreement , Code will be added to the response header : Connection:keep-alive
The difference between long links and short links
Short connection : Create connection -> To transmit data -> Close the connection
A long connection : Create connection -> To transmit data -> Keep connected -> To transmit data ->…… -> Close the connection
Use scenarios
Short link : High concurrency , Data interaction is infrequent
A long connection : Data interaction is frequent , Point to point communication
Communication mode
Short link : I'll send you a message , I have to wait until you reply to me or I can't wait for a while , The communication ends
A long connection : I'll send you a message , Keep communicating , During the period of maintaining communication , You replied to me while I was doing other things , I can tell you what you replied to me immediately , Then you can respond or not respond , Keep doing things
WebSocket agreement
WebSocket yes HTML5 Start by offering one in a single TCP A protocol for full duplex communication on a connection .
What is full duplex : full duplex (Full Duplex) It's a term for communication transmission . Both parties allow data to be transmitted simultaneously in both directions during communication , It is equivalent in capability to the combination of two simplex communication modes . Full duplex refers to the two-way transmission of signals at the same time . finger A→B At the same time B→A, It's like a two-way drive .
Simplex : It's like a one-way street for cars , Only Party A is allowed to transmit information to Party B , And Party B can't transmit to Party A .
In the implementation technology of push function , Compared with Ajax The way of regular polling (setInterval),WebSocket Save server resources and bandwidth .
stay WebSocket in , The browser and the server only need to complete a handshake , You can create persistent connections , And two-way data transmission .
websocket Common event methods
var Socket = new WebSocket(url, [protocol] );
WebSocket event
Here are WebSocket Object related events . Suppose we created it using the above code Socket object :
WebSocket Method 
Case code
// Appoint websocket route
var websocket;
if ('WebSocket' in window) {
websocket = new WebSocket("ws://localhost:8080/Spring-websocket/ws?uid="+${
sessionScope.uid});
} else if ('MozWebSocket' in window) {
websocket = new MozWebSocket("ws://localhost:8080/Spring-websocket/ws"+${
sessionScope.uid});
} else {
websocket = new SockJS("http://localhost:8080/Spring-websocket/ws/sockjs"+${
sessionScope.uid});
}
//var websocket = new WebSocket('ws://localhost:8080/Spring-websocket/ws');
websocket.onmessage = function(event) {
var data=JSON.parse(event.data);
if(data.from>0||data.from==-1){
// User or group messages
// Receive real-time messages from the server and add them to HTML On the page
$("#log-container").append("<div class='bg-info'><label class='text-danger'>"+data.fromName+" "+data.date+"</label><div class='text-success'>"+data.text+"</div></div><br>");
// Scroll bar scrolls to the bottom
scrollToBottom();
}else if(data.from==0){
// Online news
if(data.text!="${sessionScope.username}")
{
$("#users").append('<a href="#" οnclick="talk(this)" class="list-group-item">'+data.text+'</a>');
//alert(data.text+" launched ");
}
}else if(data.from==-2){
// Offline news
if(data.text!="${sessionScope.username}")
{
$("#users > a").remove(":contains('"+data.text+"')");
//alert(data.text+" Get offline ");
}
}
};
websocket.onopen = function(event) {
debugger
//alert(' Successful connection !');
};
websocket.onclose = function(event) {
debugger
//alert(' Connection is closed !');
};
websocket.onerror = function(event) {
//alert(' link error !');
};
rely on
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
<version>4.0.5.RELEASE</version>
</dependency>
Back end code
/** * WebScoket Configure the processor */
@Component
@EnableWebSocket
public class WebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer {
@Resource
MyWebSocketHandler handler;
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(handler, "/ws").addInterceptors(new HandShake());
registry.addHandler(handler, "/ws/sockjs").addInterceptors(new HandShake()).withSockJS();
}
}
边栏推荐
猜你喜欢
随机推荐
剖析Redis中的Sentinel模式
详解各种网络协议
0回溯/动态规划中等 LeetCode526. 优美的排列
socket基础知识以及各种使用场景
详解TCP连接的释放
前缀和 LeetCode2100. 适合打劫银行的日子
C# 自定义栈(Stack)
线程池总结
Explain TCP segmentation and IP fragmentation in detail
读《凤凰架构》- RPC的历史与知识
剑*offer—— 链表逆序
HCIP---BGP ---边界网关协议
Common sorting method - Select Sorting
0动态规划 LeetCodde313. 超级丑数
LVS负载均衡调度原理及配置方法
Basic knowledge of high voltage technology
C语言也能写植物大战僵尸
Explain the interactive data flow and block data flow of TCP in detail
Unity3d:UGUI源码,Rebuild优化
DHCP 第二次实验








![[AUTOSAR storage stack NVM]](/img/7a/15e01f8ace647b55e11e764dba1b64.png)
