关于使用WebSocket

前端需要这样写

    var websocket = null;
        if('WebSocket' in window){
            websocket = new WebSocket('ws://izelong.natapp1.cc/webScoket');
        }else{
            alert("该浏览器不支持websocket!");
        }

        websocket.onopen = function(event){
            console.log("建立连接");
        }
        websocket.onclose = function(event){
            console.log("关闭连接");
        }

        websocket.onmessage = function(event){
            console.log("收到消息:" + event.data);
            //弹窗提醒,播放音乐
        }

        websocket.onerror = function(){
            alert("websocket通信发生错误!");
        }
        window.onbeforeunload = function(){
            websocket.onclose();
        }

其中we://..../webSocket 服务端遵守ws协议

服务端pom.xml需要引入websocket依赖

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

新建service 定义接口@ServerEndpoint("/webSocket")

@ServerEndpoint("/webScoket")
public class WebSocket {
    private Session session;

    private static CopyOnWriteArraySet<WebSocket> webSocketSet = new CopyOnWriteArraySet<>();

    @OnOpen
    public void onOpen(Session session){
        this.session = session;
        webSocketSet.add(this);
        log.info("【webSocket】有新的连接,总数:{}", webSocketSet.size());
    }

    @OnClose
    public void onClose(){
        webSocketSet.remove(this);
        log.info("【webSocket】连接断开,总数:{}",webSocketSet.size());
    }

    @OnMessage
    public void onMessage(String message){
        log.info("【webSocket】收到客户端发来的消息:{}",message);
    }

    public void sendMessage(String message){
        for(WebSocket webSocket:webSocketSet){
            log.info("【websocket】广播消息,message:{}",message);
            try{
                webSocket.session.getBasicRemote().sendText(message);
            } catch (IOException e){
                log.error("【websocket】发送消息异常:{}",message);
                e.printStackTrace();
            }
        }
    }
}

需要序列化pojo类,idea提供了序列化插件
引入Serializable接口
idea引入Serializable插件
修改serializable插件快捷键

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,026评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,974评论 6 342
  • 原文地址:http://www.ibm.com/developerworks/cn/java/j-lo-WebSo...
    敢梦敢当阅读 8,955评论 0 50
  • 生活无论怎样地艰难,一些家当必须有;有了家当,日子才好走。 母亲也是有家当的,全与纺织有关;计有:纺车一架,线拐一...
    沣水寒江雪阅读 618评论 1 14
  • 最近不知道为什么,很喜欢下雨天,尤其是那种瓢泼大雨。雨点声越大,心就越发平静,就容易陷入深深的回忆里… 我出生在农...
    503鸡蛋说阅读 341评论 0 1