美文网首页
Springboot WebSocket

Springboot WebSocket

作者: never_b6a7 | 来源:发表于2021-07-20 14:04 被阅读0次

1.pom

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

2.配置

@Configuration
public class WebSocketConfiguration {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

3.websocket。

@ServerEndpoint("/test")
@Component
@Slf4j
public class WebSocketController {
    private static Map<String, Session> clients = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session) {
        log.info("有新的客户端连接了: {}", session.getId());
        //将新用户存入在线的组
        clients.put(session.getId(), session);
    }

    /**
     * 客户端关闭
     * @param session session
     */
    @OnClose
    public void onClose(Session session) {
        log.info("有用户断开了, id为:{}", session.getId());
        //将掉线的用户移除在线的组里
        clients.remove(session.getId());
    }

    /**
     * 发生错误
     * @param throwable e
     */
    @OnError
    public void onError(Throwable throwable) {
        throwable.printStackTrace();
    }

    /**
     * 收到客户端发来消息
     * @param message  消息对象
     */
    @OnMessage
    public void onMessage(String message,Session session) {
        log.info(message);

        JSONObject jsonObject = JSON.parseObject(message);
        jsonObject.put("fromUserId","zzzzzzzzzzzzzz");
        log.info("服务端收到客户端发来的消息: {}", message);
        log.info("服务端收到客户端发来的消息: {}", jsonObject.toJSONString());
        this.sendAll(message);
       // this.sendAll("From serverTo all");

        this.sendMessage( message, session);
        this.sendMessage("From server",session);
    }

    /**
     * 群发消息
     * @param message 消息内容
     */
    private void sendAll(String message) {
        for (Map.Entry<String, Session> sessionEntry : clients.entrySet()) {
            sessionEntry.getValue().getAsyncRemote().sendText(message);
        }
    }
    private void sendMessage(String message, Session toSession) {
        try {
            log.info("服务端给客户端[{}]发送消息{}", toSession.getId(), message);
            toSession.getBasicRemote().sendText(message);
        } catch (Exception e) {
            log.error("服务端发送消息给客户端失败:{}", e);
        }
    }
}

4.前端

<script>
export default {
    data(){
        return{
             path:"ws://x.x.x.x:8900/test",
            socket:""
        }
    },
    mounted(){
        this._initwebscoket()
    },
    methods:{
        _initwebscoket(){
            if(typeof(WebSocket) === "undefined"){
                alert("您的浏览器不支持socket")
            }else{
                // 实例化socket
                this.socket = new WebSocket(this.path)
                // 监听socket连接
                this.socket.onopen = this.open
                // 监听socket错误信息
                this.socket.onerror = this.error
                // 监听socket消息
                this.socket.onmessage = this.getMessage
            }
        },
        open: function () {
            console.log("socket连接成功")
        },
        error: function () {
            console.log("连接错误")
        },
        getMessage: function (msg) {
            console.log(msg.data)
        },
        send: function () {
            var data={"batchid":"1123123123123123123"}
           // JSON.stringify()
           console.log(data.toString())
            this.socket.send(JSON.stringify(data))
        },
        close: function () {
            console.log("socket已经关闭")
        },
        websockettest(){
            console.log("websockettest")
        },
        closewebsockettest(){
            console.log("closewebsockettest")
        }
    },
    destroyed () {
        // 销毁监听
        this.socket.onclose = this.close
    }
}
</script>

相关文章

网友评论

      本文标题:Springboot WebSocket

      本文链接:https://www.haomeiwen.com/subject/jwolmltx.html