Websocket前后端实现

1.引入WebStocket的依赖

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

2.创建配置类 WebScoketConfig

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
 
/**
 * 开启WebSocket支持
 */
@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

新增客户的业务层
实现新增客户后,持续向前端推送客户信息。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import java.util.List;
import java.util.Map;
 
import io.recycle.modules.rest.api.dao.recycleUsersDao;
import io.recycle.modules.rest.api.entity.RecycleUsersEntity;
import io.recycle.modules.rest.api.service.RecycleUsersService;
 
 
 
@Service("recycleUsersService")
public class RecycleUsersServiceImpl implements RecycleUsersService{
 
	private static int count=0;
	@Autowired
	private NoticeWebsocket noticeWebsocket;
	@Autowired
	private RecycleUsersDao recycleUsersDao;
 
	@Override
	public void save(RecycleUsersEntity recycleUsers){
		recycleUsersDao.save(recycleUsers);
		//测试webstocket,实现新增客户往前端推送消息,直到前端回复
		boolean flag = false;
		do{
			try {
				Thread.sleep(300);    //休息300毫秒
			} catch (InterruptedException e) {
				e.printStackTrace();
				System.out.println("休息时出错000000");
			}
			//往前端发送消息
			System.out.println("count===="+count);
			boolean resultFlag = noticeWebsocket.sendMessage("新增了用户:" + recycleCustomer.toString(),count);
 
			flag = resultFlag;
 
			if (resultFlag){
				System.out.println("停止往前端发送数据,因为 resultFlag 为: "+resultFlag+"==前端已接收的消息");
			}else {
				System.out.println("往前端发送数据,因为 resultFlag 为: "+resultFlag+"==说明前端还没接收到消息");
			}
 
 
		}while ( !flag );
		System.out.println("停止往前端发数据,因为 delFlag 为: "+flag);
		count = count +1;
 
 
	}
}

3.创建WebScoketConfigServer
在websocket协议下,后端服务器等于是客户端,需要用@ServerEndpoint指定访问的路径,并使用@Component注入容器。

这里实现新增 客户,持续向前端推送客户信息,直到前端收到消息,并回复收到。

import com.alibaba.fastjson.JSONObject;
import io.recycle.modules.rest.api.dao.RecycleUsersDao;
import io.recycle.modules.rest.api.dto.websocket.NoticeWebsocketResp;
import io.recycle.modules.rest.api.entity.RecycleUsersEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
 
/**
 * @ServerEndpoint 注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端,
 * 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
 */
@ServerEndpoint("/chepaisend")
@Component
@Slf4j
public class NoticeWebsocket {
 
    //连接客户端
    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 (NoticeWebsocket.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){
            NoticeWebsocketResp noticeWebsocketResp = new NoticeWebsocketResp();
            noticeWebsocketResp.setNoticeType(noticeType);
            sendMessage(noticeWebsocketResp);
            sum = count;
        }
        //判断前端是否 回复了 收到消息  相等没收到,不相等 收到
        if (initFlag==tempFlag){
            NoticeWebsocketResp noticeWebsocketResp = new NoticeWebsocketResp();
            noticeWebsocketResp.setNoticeType(noticeType);
            sendMessage(noticeWebsocketResp);
        }else {
            //收到消息了,别发同一个消息了
            tempFlag = initFlag;
            return true;
        }
        tempFlag = initFlag;
        //没收到消息继续发
        return false;
    }
 
 
    /**
     * 发送给所有用户
     * @param noticeWebsocketResp
     */
    public static void sendMessage(NoticeWebsocketResp noticeWebsocketResp){
        String message = JSONObject.toJSONString(noticeWebsocketResp);
        for (Session session1 : NoticeWebsocket.clients.values()) {
            try {
                session1.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
 
    /**
     * 根据用户id发送给某一个用户
     * **/
    public static void sendMessageByUserId(String userId, NoticeWebsocketResp noticeWebsocketResp) {
        if (!StringUtils.isEmpty(userId)) {
            String message = JSONObject.toJSONString(noticeWebsocketResp);
            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();
    }
 
}

封装的发送消息的对象

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
 
@Data
@ApiModel("ws通知返回对象")
public class NoticeWebsocketResp<T> {
 
    @ApiModelProperty(value = "通知类型")
    private String noticeType;
 
    @ApiModelProperty(value = "通知内容")
    private T noticeInfo;
 
}

4.WebSocket调用
用户发送消息给后端,,后端接收到消息后再主动推送给指定/全部用户,可以实现消息的私聊和群发功能。

import io.recycle.common.utils.R;
import io.recycle.modules.rest.api.service.impl.NoticeWebsocket;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
@RequestMapping("/mytest")
public class OrderController {
	@GetMapping("/test")
    public R test() {
    	NoticeWebsocket.sendMessage("你好啊,WebSocket",1);
        return R.ok();
    }
}

前端连接

<!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:8191/double-win/chepaisend');
// 获取连接状态
        console.log('连接状态:' + ws.readyState);
//监听是否连接成功
        ws.onopen = function () {
            console.log('连接状态:' + 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.readyState);
            reconnect();
 
        }
// 监听并处理error事件
        ws.onerror = function (error) {
            console.log(error);
        }
    }
    function reconnect() {
        limitConnect ++;
        console.log("重连第" + limitConnect + "次");
        setTimeout(function(){
            init();
        },2000);
 
    }
</script>
</html>
 
  • 24
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值