springboot 2.x 一下版本添加 websocket

1.  引入jar包

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

2. 

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();
    }

}

3. 

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Component;


@Slf4j
@ServerEndpoint(value = "/websocket/{shopId}")
@Component
public class WebSocketServer {

    private static int onlineCount = 0;

    private static ConcurrentHashMap<String, CopyOnWriteArraySet<WebSocketServer>> webSocketSetMap = new ConcurrentHashMap<String, CopyOnWriteArraySet<WebSocketServer>>();

    private Session session;

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("shopId") String shopId) {
        this.session = session;
        CopyOnWriteArraySet<WebSocketServer> webSocketSet = webSocketSetMap.get(shopId);
        if (CollectionUtils.isEmpty(webSocketSet)) {
            webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
        }
        webSocketSet.add(this);
        webSocketSetMap.put(shopId, webSocketSet);
        addOnlineCount();
        log.info("有新连接加入,门店号:{}, sessionId:{}, 当前在线人数为:{}", shopId, session.getId(), getOnlineCount());
        try {
            sendMessage("连接成功");
        } catch (IOException e) {
            log.error("websocket IO异常");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(@PathParam("shopId") String shopId) {
        CopyOnWriteArraySet<WebSocketServer> webSocketSet = webSocketSetMap.get(shopId);
        if (!CollectionUtils.isEmpty(webSocketSet)) {
            webSocketSet.remove(this);
        }
        subOnlineCount();
        log.info("有一连接关闭,门店号:{}, sessionId:{},当前在线人数为", shopId, this.session.getId(), getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message) {
        log.info("来自客户端的消息:" + message);
    }

    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
    }


    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }


    /**
     * 群发自定义消息
     */
    public static void sendInfo(String message, String shopId) throws IOException {
        log.info(message);
        CopyOnWriteArraySet<WebSocketServer> webSocketSet = webSocketSetMap.get(shopId);
        if (CollectionUtils.isEmpty(webSocketSet)) {
            return;
        }
        for (WebSocketServer item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                continue;
            }
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }


}

 

4. 

@RestController
@RequestMapping("/rf")
public class SocketController {

    @Autowired
    private RfApiClient rfApiClient;

    /**
     * 长连接推送数据接口
     *
     * @param shopId
     * @param message
     * @return
     */
    @RequestMapping(value = "/push/{shopId}", method = RequestMethod.GET)
    public String pushToWeb(@PathVariable("shopId") String shopId, @RequestParam("message") String message) {
        try {
            WebSocketServer.sendInfo(message, shopId);
        } catch (IOException e) {
            e.printStackTrace();
            return message;
        }
        return message;
    }

}

 

5. 浏览器 js 测试    

var socket;
        if(typeof(WebSocket) == "undefined") {
            console.log("您的浏览器不支持WebSocket");
        }else{
            console.log("您的浏览器支持WebSocket");
            //实现化WebSocket对象,指定要连接的服务器地址与端口  建立连接
            socket = new WebSocket("ws://localhost:20000/websocket/00144");
            //打开事件
            socket.onopen = function() {
                console.log("Socket 已打开");
                //socket.send("这是来自客户端的消息" + location.href + new Date());
            };
            //获得消息事件
            socket.onmessage = function(msg) {
                console.log(msg.data);
                //发现消息进入    调后台获取
                getCallingList();
            };
            //关闭事件
            socket.onclose = function() {
                console.log("Socket已关闭");
            };
            //发生了错误事件
            socket.onerror = function() {
                alert("Socket发生了错误");
            }
             $(window).unload(function(){
                  socket.close();
                });

        }


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值