![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-PRd8ZkqJ-1693291730114)(C:\Users\13301\AppData\Roaming\Typora\typora-user-images\image-20230829143057984.png)]](https://1000bd.com/contentImg/2024/04/07/ba5f7b6b3040289e.png)
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-8Dz61vLO-1693291730115)(C:\Users\13301\AppData\Roaming\Typora\typora-user-images\image-20230829143146449.png)]](https://1000bd.com/contentImg/2024/04/07/4b92946caa4c4514.png)
function createScoket(token){
var socket;
if(typeof(WebSocket) == "undefined") {
console.log("您的浏览器不支持WebSocket");
}else{
var host = window.location.origin.replace("http:","ws:")
//实现化WebSocket对象,指定要连接的服务器地址与端口 建立连接
socket = new WebSocket(host+":9000/ws/"+token);
//打开事件
socket.onopen = function() {
console.log("Socket 已打开");
//socket.send("这是来自客户端的消息" + location.href + new Date());
};
//获得消息事件
socket.onmessage = function(result) {
console.log("客户端收到服务端发送的消息: " + result);
console.log("result.data: " + result.data);
};
//关闭事件
socket.onclose = function() {
console.log("Socket已关闭");
};
//发生了错误事件
socket.onerror = function() {
console.log("Socket发生了错误");
}
//窗口关闭
$(window).unload(function(event){
socket.close();
});
}
return socket;
}
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>客户端Atitle>
<script src="jquery.js">script>
<script src="socket.js">script>
<script>
var socket;
function connect() {
if (!socket) {
// 建立socket链接的唯一标识
socket = createScoket("123");
}
}
function sendMessage() {
var content = $("#content").val();
socket.send(content);
}
script>
head>
<body>
<input type="button" value="链接服务器" onclick="connect()" /> <br>
<input type="text" id="content"> <input type="button" value="发送消息" onclick="sendMessage()" />
body>
html>
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>客户端Btitle>
<script src="jquery.js">script>
<script src="socket.js">script>
<script>
var socket;
function connect() {
if (!socket) {
// 建立socket链接的唯一标识
socket = createScoket("234");
}
}
function sendMessage() {
var content = $("#content").val();
socket.send(content);
}
script>
head>
<body>
<input type="button" value="链接服务器" onclick="connect()" /> <br>
<input type="text" id="content"> <input type="button" value="发送消息" onclick="sendMessage()" />
body>
html>
需要引入websocket的依赖
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-websocketartifactId>
dependency>
WebSocketServer.class 这里编写websocket根据前端做长连接的接口地址
package com.xiaoge;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.ConcurrentHashMap;
/**
* todo 类里面这几个方法注解事件, 对应着前端相同的事件
*/
@ServerEndpoint("/ws/{token}") // 这个注解相当于RequestMapping, 写路径, 这个路径跟前端约定好的, 可以看前端项目的socket.js文件里面的createScoket方法
@Component
public class WebSocketServer {
private Session session;
public static ConcurrentHashMap<String,Session> clients = new ConcurrentHashMap<>();
/**
* 建立socket链接
* @param session
* @param token
*/
@OnOpen
public void onOpen(Session session, @PathParam( "token") String token){
// 建立和浏览器的会话映射关系
System.out.println("浏览器和服务器建立连接");
clients.put(token,session);
}
/**
* 接收客户端发送的消息
* @param msg
*/
@OnMessage
public void onMessage(@PathParam( "token") String token, String msg) {
System.out.println("收到客户端标识为: "+ token +"发送的消息: " + msg);
}
/**
* 关闭socket链接
* @param token
*/
@OnClose
public void onClose(@PathParam( "token") String token){
System.out.println("浏览器和服务器断开连接");
clients.remove(token);
}
/**
* socket报错
*
* @param error
*/
@OnError
public void onError(Throwable error) {
error.printStackTrace();
}
}
启动类型上, 把ServerEndpointExporter注入到IOC, 就会扫描我们贴了@ServerEndpoint注解的类, 把它的地址发布出去
package com.xiaoge;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* TODO
*
* @author Zhang Xiao
* @since
*/
@SpringBootApplication
public class WebsocketServerApplication {
public static void main(String[] args) {
SpringApplication.run(WebsocketServerApplication.class, args);
}
/**
* 扫描我们贴了@ServerEndpoint注解的类, 把它的地址发布出去
* @return
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
MessageController.class 通过这个/sendMsg接口对跟socket长连接的前端通信
package com.xiaoge;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.websocket.Session;
import java.io.IOException;
/**
* TODO
*
* @author Zhang Xiao
* @since
*/
@RestController
public class MessageController {
/**
* todo 访问这个接口的时候, websocket就会给跟websocket建立连接的客户变标识为token的发送消息
* @param token
* @param msg
* @return
* @throws IOException
*/
@GetMapping("/sendMsg")
public String sendMessage(String token, String msg) throws IOException {
Session session = WebSocketServer.clients.get(token);
// 正常应该需要判断session是否为空, 但是我这里就不判断了
session.getBasicRemote().sendText(msg);
return "消息发送成功!";
}
}
客户端A/B链接后端socket
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-CmHOI7cN-1693291730116)(C:\Users\13301\AppData\Roaming\Typora\typora-user-images\image-20230829144515875.png)]](https://1000bd.com/contentImg/2024/04/07/ab46e400184ac1b6.png)
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-YvPJ1jBP-1693291730116)(C:\Users\13301\AppData\Roaming\Typora\typora-user-images\image-20230829144559640.png)]](https://1000bd.com/contentImg/2024/04/07/2c098622555d4591.png)
客户端A/B给socket发送消息
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-RMBsES98-1693291730116)(C:\Users\13301\AppData\Roaming\Typora\typora-user-images\image-20230829144653456.png)]](https://1000bd.com/contentImg/2024/04/07/17b59c430dee59cc.png)
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-WD2Bevx1-1693291730116)(C:\Users\13301\AppData\Roaming\Typora\typora-user-images\image-20230829144707202.png)]](https://1000bd.com/contentImg/2024/04/07/1d2ab44b6a911140.png)
后端给前端发送消息
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-U2lGIV7y-1693291730117)(C:\Users\13301\AppData\Roaming\Typora\typora-user-images\image-20230829144752955.png)]](https://1000bd.com/contentImg/2024/04/07/6a4cf482345e6ad0.png)
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-wPARSEiq-1693291730117)(C:\Users\13301\AppData\Roaming\Typora\typora-user-images\image-20230829144823572.png)]](https://1000bd.com/contentImg/2024/04/07/c57087d38789400e.png)

客户端通过nginx, 使用ip_hash到对应的webSocket服务, 应用程序通过mq广播模式发送到每一台webSocket服务, 总有一台是保存了, 对应的用户长连接的, 它会把消息通知给前端。
客户端不是关闭浏览器, 那样socket就没有被删除, 它只是断网了, 你不知道它还需不需要这个socket, 长此以往下去, 容易内存溢出, 这时候就需要心跳机制, 每隔一段时间发送一次心跳, 更新心跳时间, 这样就知道那些socket有用, 那些socket没用, 这样就可以把对应的socket链接删除。
demo地址: https://download.csdn.net/download/zsx1314lovezyf/88269081?spm=1001.2014.3001.5503