springboot配置websocket

1. 创建WebSocketServer
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@ServerEndpoint(value = "/websocket/{openid}")
@Component
public class WebSocketServer {
    @PostConstruct
    public void init() {
        System.out.println("websocket 加载");
    }
    private static final AtomicInteger OnlineCount = new AtomicInteger(0);
    public static final ConcurrentHashMap<String,Session> USER_MAP = new ConcurrentHashMap<String,Session>();

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session,@PathParam("openid") String openid) {
        USER_MAP.put(openid,session);
        int cnt = OnlineCount.incrementAndGet();
        System.out.println("有连接加入:" + openid + ";当前连接数为:" + cnt);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session,@PathParam("openid") String openid) {
        try {
            USER_MAP.remove(openid);
            session.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        int cnt = OnlineCount.decrementAndGet();
        System.out.println("有连接关闭:" + openid + ";当前连接数为:" + cnt);
    }

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

    /**
     * 出现错误
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error, @PathParam("openid") String openid) {
        System.out.println("发生错误:Session ID:" + session.getId() + " oprnid: " + openid);
        error.printStackTrace();
    }

    public static void sendMessage(String message,String openid) throws IOException {
        if(StringUtils.isBlank(openid)) {
            return;
        }
        Session session = USER_MAP.get(openid);
        if(session != null){
            System.out.println(openid + " 有未读条数: " + message);
            session.getBasicRemote().sendText(message);
        }
    }

    //给所有的会话发消息
    public static void sendAllMessage() throws IOException {
        Collection<Session> list = USER_MAP.values();
        for(Session session : list) {
            session.getBasicRemote().sendText("0");
        }
    }
}

WebSocketServer 中的静态方法可直接调用,例如:WebSocketServer.sendAllMessage();

2. 测试websocket的html代码
<!DOCTYPE HTML>
<html>
<head>
<title>My WebSocket</title>
</head>

<script type="text/javascript">
    var websocket = null;

    //判断当前浏览器是否支持WebSocket, 主要此处要更换为自己的地址
    if ('WebSocket' in window) {
        websocket = new WebSocket("ws://localhost:18092/test/one");
    } else {
        alert('Not support websocket')
    }

    //连接发生错误的回调方法
    websocket.onerror = function() {
        
    };

    //连接成功建立的回调方法
    websocket.onopen = function(event) {
        setMessageInnerHTML("open");
    }

    //接收到消息的回调方法
    websocket.onmessage = function(event) {
        setMessageInnerHTML(event.data);
    }

    //连接关闭的回调方法
    websocket.onclose = function() {
        setMessageInnerHTML("close");
    }

    //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
    window.onbeforeunload = function() {
        websocket.close();
    }

    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML) {
        console.log(innerHTML)
    }

    //关闭连接
    function closeWebSocket() {
        websocket.close();
    }

    //发送消息
    function send() {
        var message = document.getElementById('text').value;
        websocket.send(message);
    }
</script>
</html>

如果需要nginx配置wss跳转。点击跳转到nginx配置wws访问websocket服务

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值