websocket 前+后端协调demo

       今天写代码得时候,我又按照往常得习惯用了一个技术 就习惯性把技术文档做成word.......并收藏起来,方便自己查阅,因为我自己记性比较差所以自己就偏爱这种方式记录点滴~~~,(导致自己收藏了好多~~~~),感觉独乐乐不如众乐乐,就想着把一些技术分享给刚入行得朋友,因为这个也是我作为萌新刚毕业时候一点一点的积累起来的,希望可以帮助到别人。


一:什么是WebSocket

  • WebSocket是HTML5下一种新的协议(websocket协议本质上是一个基于tcp的协议)
  • 它实现了浏览器与服务器全双工通信,能更好的节省服务器资源和带宽并达到实时通讯的目的
  • Websocket是一个持久化的协议

二:websocket的原理 

  1. websocket约定了一个通信的规范,通过一个握手的机制,客户端和服务器之间能建立一个类似tcp的连接,从而方便它们之间的通信
  2. 在websocket出现之前,web交互一般是基于http协议的短连接或者长连接
  3. websocket是一种全新的协议,不属于http无状态协议,协议名为"ws

        优点:减少资源消耗;实时推送不用等待客户端的请求;减少通信量;
        缺点:少部分浏览器不支持,不同浏览器支持的程度和方式都不同。  

        应用场景:智慧大屏,消息提醒通知等

三:代码实现:

1.添加依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

2.socket发送实体类

/**
 * @Author: mark
 * @Description: TODO
 * @Date: 2023/05/24/11:37
 * @Version: 1.0
 */
@Data//自己随意定义属性
public class MessageBean {
    String type;
    String mes;
}

3.socket配置类

import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Component
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }
}
4.Websocket服务端
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
 
/**
 * @ServerEndpoint 注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端,
 * 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
 */
@ServerEndpoint("/Websocket")
@Component
@Slf4j
public class Websocket {
 
    //记录连接的客户端
    public static Map<String, Session> clients = new ConcurrentHashMap<>();
 
    /**
     * userId关联sid(解决同一用户id,在多个web端连接的问题)
     */
    public static Map<String, Set<String>> conns = new ConcurrentHashMap<>();
 
    private String sid = null;
 
 
 
 
    //一些记录发送消息状态
    private static int initFlag =0;
 
    private static int tempFlag =0;
    //区分新旧消息的变量
    private static int sum=0;
    /**
     * 连接成功后调用的方法
     * @param session
     *
     */
    @OnOpen
    public void onOpen(Session session) {
        this.sid = UUID.randomUUID().toString();
 
        clients.put(this.sid, session);
 
        log.info(this.sid + "连接开启!");
    }
 
    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        log.info(this.sid + "连接断开!");
        clients.remove(this.sid);
    }
 
    /**
     * 判断是否连接的方法
     * @return
     */
    public static boolean isServerClose() {
        if (Websocket.clients.values().size() == 0) {
            log.info("已断开");
            return true;
        }else {
            log.info("已连接");
            return false;
        }
    }
 
    /**
     * 发送给所有用户
     * @param noticeType
     */
 
    public static boolean sendMessage(String noticeType,int count){

        if (sum != count){
            WebsocketResp noticeWebsocketResp = new WebsocketResp();
            noticeWebsocketResp.setNoticeType(noticeType);
            sendMessage(noticeWebsocketResp);
            sum = count;
        }
        //判断前端是否 回复了 收到消息  相等没收到,不相等 收到
        if (initFlag==tempFlag){
            WebsocketResp noticeWebsocketResp = new WebsocketResp();
            noticeWebsocketResp.setNoticeType(noticeType);
            sendMessage(noticeWebsocketResp);
        }else {
            tempFlag = initFlag;
            log.info("收到消息了,别发同一个消息了");
            return true;
        }
        tempFlag = initFlag;
        log.info("没收到消息继续发");
        return false;
    }
 
 
    /**
     * 发送给所有用户
     * @param websocketResp
     */
    public static void sendMessage(WebsocketResp websocketResp){
        String message = JSONObject.toJSONString(websocketResp);
        for (Session session1 : Websocket.clients.values()) {
            try {
                session1.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
 
    /**
     * 根据用户id发送给某一个用户
     * **/
    public static void sendMessageByUserId(String userId, WebsocketResp websocketResp) {
        if (!StringUtils.isEmpty(userId)) {
            String message = JSONObject.toJSONString(websocketResp);
            Set<String> clientSet = conns.get(userId);
            if (clientSet != null) {
                Iterator<String> iterator = clientSet.iterator();
                while (iterator.hasNext()) {
                    String sid = iterator.next();
                    Session session = clients.get(sid);
                    if (session != null) {
                        try {
                            session.getBasicRemote().sendText(message);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
 
 
    /**
     * 收到客户端消息后调用的方法
     * @param message
     * @param session
     */
 
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("收到来自窗口"+"的信息:"+message);
        if ("已接收到消息".equals(message)){
            //收到消息,改变flag的值
            System.out.println("前端已经收到消息,开始改变 initFlag的值,此时initFlag= "+initFlag);
            initFlag = initFlag +1;
            System.out.println("前端已经收到消息,已经改变 initFlag的值,此时initFlag== "+initFlag);
        }
 
    }
 
    /**
     * 发生错误时的回调函数
     * @param error
     */
    @OnError
    public void onError(Throwable error) {
        log.info("错误");
        error.printStackTrace();
    }

5.test小测一下

   5.1:控制层

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


/**
 * @Author mark
 * @Description TODO
 * @Date 2023/05/24/14:51
 * @Version 1.0
 */

@RestController
@RequestMapping("/socket")
public class SoketCmd {

    @Autowired
    RecycleCustomerService recycleCustomerService;

	@GetMapping("/test")
    public ResponseResult test() {
        MessageBean messageBean = new MessageBean();
        messageBean.setType("aaaa");
        messageBean.setMes("电压过高");
        recycleCustomerService.sendMes(messageBean);
        return Response.OK();
    }
}

    5.2:接口层



/**
 * @Author: mark
 * @Description: TODO
 * @Date: 2023/05/24/13:47
 * @Version: 1.0
 */
public interface RecycleCustomerService {
     void sendMes(MessageBean messageBean);
}

  5.3实现层

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service("recycleCustomerService")
@Slf4j
public class RecycleCustomerServiceImpl implements RecycleCustomerService {
 
	private static int count=0;
	@Autowired
	private Websocket websocket;

 
	@Override
	public void sendMes(MessageBean messageBean){
		//测试webstocket,实现新增客户往前端推送消息,直到前端回复
		boolean flag = false;
		do{
			try {
				Thread.sleep(300);    //休息300毫秒
			} catch (InterruptedException e) {
				e.printStackTrace();
				log.error("休息时出错~~~~~~~");
			}
			//往前端发送消息
			boolean resultFlag = websocket.sendMessage("实时数据:" + messageBean.toString(),count);
 
			flag = resultFlag;
 
			if (resultFlag){
				log.info("停止往前端发送数据,因为 resultFlag 为:{},说明前端接收到消息",resultFlag);
			}else {
				log.info("往前端发送数据,因为 resultFlag 为:{}",resultFlag);
			}
		}while ( !flag );
		log.info("停止往前端发送数据,因为 delFlag 为:{}",flag);
		count = count +1;
	}

最后创建一个html文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>SseEmitter</title>
</head>
<body>
<div id="message"></div>
</body>
<script>
    var limitConnect = 0;
    init();
    function init() {
        //开启webstocket服务的ip地址  ws:// + ip地址 + 访问路径
        var ws = new WebSocket('ws://127.0.0.1:11002/Websocket');
// 获取连接状态
        console.log('ws连接状态:' + ws.readyState);
//监听是否连接成功
        ws.onopen = function () {
            console.log('ws连接状态:' + ws.readyState);
            limitConnect = 0;
            //连接成功则发送一个数据
            ws.send('我们建立连接啦');
        }
// 接听服务器发回的信息并处理展示
        ws.onmessage = function (data) {
            console.log('接收到来自服务器的消息:');
            console.log(data);
            //接收到 消息后给后端发送的 确认收到消息,后端接收到后 不再重复发消息
            ws.send('已接收到消息');
            //完成通信后关闭WebSocket连接
            // ws.close();
        }
// 监听连接关闭事件
        ws.onclose = function () {
            // 监听整个过程中websocket的状态
            console.log('ws连接状态:' + ws.readyState);
            reconnect();
 
        }
// 监听并处理error事件
        ws.onerror = function (error) {
            console.log(error);
        }
    }
    function reconnect() {
        limitConnect ++;
        console.log("重连第" + limitConnect + "次");
        setTimeout(function(){
            init();
        },2000);
 
    }
</script>
</html>
 

服务启动,然后打开html文件F12就可以看到效果啦~

这是我测试的效果图:

 我尽量写的完整一点希望对大家有用!!!

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值