当前位置:网站首页>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();
}
}
边栏推荐
猜你喜欢

Hcip --- BGP --- border gateway protocol

Unity在URP管线下使用TriLib插件加载模型材质不正确的问题

unity3d:Assetbundle模拟加载,同步加载,异步加载,依赖包加载,自动标签,AB浏览器,增量打包

Unity3D+moba+技能指示器(一)

WebSocket 协议讲解

HCIP---MGRE环境下的OSPF综合实验

【无标题】

@RequiredArgsConstructor注解使用

unity3d:向量计算,AOE图形相交
![[bootloader architecture and brushing process based on UDS service]](/img/c7/de4f1e32f89173e18d74d2f624f3f9.png)
[bootloader architecture and brushing process based on UDS service]
随机推荐
*offer--2
[AUTOSAR DCM 1. module introduction (DSL, DSD, DSP)]
线程池总结
Unity3D高清渲染管线无法在模型上播放视频
DHCP 第二次实验
Vs attribute configuration related knowledge
剑指 Offer做题总结
Analyze redis cluster
HCIP---HCIA知识回顾(一)
《Kubernetes in Action》第二章笔记
Unity3d+GameFramework:资源分析,资源依赖,循环依赖检测
刷题笔记:二叉树剪枝(递归,迭代)
@RequiredArgsConstructor注解使用
[fee of AUTOSAR (difference between nonvolatile memory flash and EEPROM)]
C custom set
SQL基础操作总结
How to write a web page with a common text editor
第五周作业
WebSocket 协议讲解
并发编程1-2