首页 > 其他分享 >websocket

websocket

时间:2022-08-30 11:57:58浏览次数:63  
标签:websocket log public session import id

maven

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

 

WebSocketConfig

package com.new3s.common.framework.socket;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/**
 * @Description webSocket 配置类
 * @Date 2022-08-27
 * @Author xie
 */
@Configuration
@EnableWebSocket
public class WebSocketConfig {

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

}

 

WebSocketServer

package com.new3s.pvinspection.socket;

import com.new3s.common.core.exception.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Description WebSocket 服务
 * @Date 2022-08-27
 * @Author xie
 */
@ServerEndpoint("/websocket/pv/airline/{uid}")
@Component
public class AirlineWebSocketServer {

    private static Logger log = LoggerFactory.getLogger(AirlineWebSocketServer.class);

    private static final AtomicInteger onlineNum = new AtomicInteger(0);

    private static CopyOnWriteArraySet<Session> sessionPools = new CopyOnWriteArraySet<>();

    @OnOpen
    public void onOpen(Session session, @PathParam(value = "uid") String uid) {

        sessionPools.add(session);
        onlineNum.incrementAndGet();
        log.info("{}: 加入到websocket. 当前连接数:{}", uid, onlineNum);

        try {
            sendMessage(session, "WebSocket连接成功");
        } catch (IOException e) {
            log.error("WebSocket IO异常");
        }
    }

    @OnClose
    public void onClose(Session session) {
        sessionPools.remove(session);
        onlineNum.decrementAndGet();
        log.info("有连接关闭, 当前连接数:{}", onlineNum);
    }

    @OnError
    public void one rror(Session session, Throwable exception) {
        log.error("连接错误:{}", exception);
        throw new ServiceException(exception.getMessage());
    }

    @OnMessage
    public void onMessage(Session session, String message) {
        log.info("来自客户端的消息:" + message);
        try {
            //sendMessage(session, message);
            broadCastInfo(message);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("发送WebSocket IO异常: {}", e);
        }

    }

    public void sendMessage(Session session, String message) throws IOException {
        if (null != session) {
            synchronized (session) {
                session.getBasicRemote().sendText(message);
            }
        }
    }

    public void broadCastInfo(String message) throws IOException {
        for (Session session : sessionPools) {
            if (session.isOpen()) {
                sendMessage(session, message);
            }
        }
    }

}

 

websocket测试

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>实时监控</title>
    </head>
    <style>
        .item {
            display: flex;
            border-bottom: 1px solid #000000;
            justify-content: space-between;
            width: 30%;
            line-height: 50px;
            height: 50px;
        }


        .item span:nth-child(2){
            margin-right: 10px;
            margin-top: 15px;
            width: 20px;
            height: 20px;
            border-radius: 50%;
            background: #55ff00;
        }
        .nowI{
            background: #ff0000 !important;
        }
</style>
    <body>
        <div id="app">
            <div v-for="item in list" class="item">
                <span>{{item.id}}.{{item.name}}</span>
                <span :class='item.state==-1?"nowI":""'></span>
            </div>
        </div>
    </body>
    <script src="./js/vue.js"></script>
    <script type="text/javascript">
        var vm = new Vue({
            el: "#app",
            data: {
                list: [{
                        id: 1,
                        name: '张三',
                        state: 1
                    },
                    {
                        id: 2,
                        name: '李四',
                        state: 1
                    },
                    {
                        id: 3,
                        name: '王五',
                        state: 1
                    },
                    {
                        id: 4,
                        name: '韩梅梅',
                        state: 1
                    },
                    {
                        id: 5,
                        name: '李磊',
                        state: 1
                    },
                ]
            }
        })


        var webSocket = null;
        if ('WebSocket' in window) {
            //创建WebSocket对象
            webSocket = new WebSocket("ws://localhost:8080/websocket/pv/airline/" + getUUID());


            //连接成功
            webSocket.onopen = function() {
                console.log("已连接");
                webSocket.send("消息发送测试")
            }
            //接收到消息
            webSocket.onmessage = function(msg) {
                //处理消息
                var serverMsg = msg.data;
                var t_id = parseInt(serverMsg)    //服务端发过来的消息,ID,string需转化为int类型才能比较
                for (var i = 0; i < vm.list.length; i++) {
                    var item = vm.list[i];
                    if(item.id == t_id){
                        item.state = -1;
                        vm.list.splice(i,1,item)
                        break;
                    }
                }
            };


            //关闭事件
            webSocket.onclose = function() {
                console.log("websocket已关闭");
            };
            //发生了错误事件
            webSocket.onerror = function() {
                console.log("websocket发生了错误");
            }
        } else {
            alert("很遗憾,您的浏览器不支持WebSocket!")
        }


        function getUUID() {    //获取唯一的UUID
            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {


                var r = Math.random() * 16 | 0,
                    v = c == 'x' ? r : (r & 0x3 | 0x8);
                return v.toString(16);
            });
        }
</script>
</html>

 

标签:websocket,log,public,session,import,id
From: https://www.cnblogs.com/mask-xiexie/p/16638782.html

相关文章

  • 使用websocket实现协同编辑
    ​1、协同编辑的意思是什么?其实,协同编辑无非就是字面意思,多人同时编辑,并且能够同步看到对方问保存的数据,典型的例子可以参考石墨文档,腾讯文档。2、技术解决核心技术就......
  • 即时通讯源码(基于websocket即时通讯源码uniapp)+视频搭建教程
    即时通讯系统源码服务器端构架目录:1、构建基本服务器2、用户在线功能3、用户消息广播机制4、用户业务层封装5、在线用户查询6、修改用户名......
  • websockets html5 全双工通信
    常见传输协议 不够全面会陆续补充协议链接面向默认端口备注HTTPTCP链接网页80超文本传输协议FTPTCP链接文件21文件传输协议WebSocketsTCP链......
  • springboot2.4.x websocket跨域问题
    1,springboot升级版本以后websocket连接出现以下错误java.lang.IllegalArgumentException:WhenallowCredentialsistrue,allowedOriginscannotcontainthespecialv......
  • websocket的简单使用
    程序git:https://gitee.com/juncaoit/websocketpro 1.引入pom<dependency><groupId>org.springframework.boot</groupId><arti......