记录websocket以及线程池结合用的功能

pom.xml

   <!--引入alibaba的json-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
        </dependency>

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

1.初始化保活任务

package com.test.service.websokctservice;
import com.test.entity.websocket.DrivePropertiesBean;
import com.test.mapper.SubscriptionMapper;
import com.test.untils.Config;
import com.test.untils.FileUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;

/**
 * 初始化保活任务
 */
@Component
public class InitExcuteRelevant implements InitializingBean {

 
    @Autowired
    private SubscriptionMapper subscriptionMapper;

    /**
     * InitializingBean 接口中的afterPropertiesSet方法用来在设置完所有bean属性后调用
     *
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println( "-----------------开始线程-------------------------" );

        DrivePropertiesBean drivePropertiesBean = new DrivePropertiesBean();
        //http
        drivePropertiesBean.setSubscriptionUrlPre(Config.getPhotoUrl("allUrl.urlPre"));
        //门禁记录推送的订阅接口
        drivePropertiesBean.setSubscriptionUrlAft( Config.getPhotoUrl("alarm.subscriptionUrlAft") );
        //订阅刷新时输入的有效时间
        drivePropertiesBean.setSubscriptionRefreshTime( Config.getPhotoUrl("alarm.subscriptionRefreshTime") );
        //订阅间隔时间
        drivePropertiesBean.setUpdateSubscriptionTime( Config.getPhotoUrl("alarm.updateSubscriptionTime") );
        //接收服务端口号
        drivePropertiesBean.setServerSocketPort( Config.getPhotoUrl("alarm.serverSocket.port") );
        //数据接收推送的服务器地址类型
        drivePropertiesBean.setAddressType( Config.getPhotoUrl("alarm.equipment.addressType") );
        //订阅类型
        drivePropertiesBean.setSubscriptionType( Config.getPhotoUrl("alarm.subscription.type") );
        //初始化订阅时间
        drivePropertiesBean.setSubscriptionInitTime( Config.getPhotoUrl("alarm.subscriptionInitTime") );
        //订阅的库id数目,此为最大
        drivePropertiesBean.setSubscribePersonConditionLibIDNum( Config.getPhotoUrl("alarm.subscribePersonCondition.libIDNum") );
        //订阅传入的端口号
        drivePropertiesBean.setPort( Config.getPhotoUrl("alarm.equipment.port") );
        //订阅传入的id
        drivePropertiesBean.setEquipmentIp( Config.getPhotoUrl("alarm.equipment.ip") );
        //结果码(可控制开门)0:不开门, 1:开门
        drivePropertiesBean.setResultCode( Config.getPhotoUrl("allUrl.resultCode") );
        //经过时刻:范围[0, 18] 终端上报过人记录中的时间
        drivePropertiesBean.setPassTime( Config.getPhotoUrl("allUrl.passTime") );
        //人机显示信息行数最大为2,当前最多显示两行
        drivePropertiesBean.setShowInfoNum( Config.getPhotoUrl("allUrl.showInfoNum") );
        //请求路径
        drivePropertiesBean.setgUIShowInfoUrl( Config.getPhotoUrl("allUrl.gUIShowInfoUrl") );
        //设备ip及端口号
        drivePropertiesBean.setShowInfoUrl(Config.getPhotoUrl("allUrl.showInfoUrl"));
        StartThread s = new StartThread( drivePropertiesBean, subscriptionMapper);
        s.setDaemon( true );// 设置线程为后台线程,tomcat不会被hold,启动后依然一直监听。
        s.start();
    }

}
package com.test.service.websokctservice;


import com.test.entity.websocket.DrivePropertiesBean;
import com.test.mapper.SubscriptionMapper;


import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class StartThread extends Thread {

    private DrivePropertiesBean drivePropertiesBean;

    private SubscriptionMapper subscriptionMapper;

    private PersonTableService personTableService;

    private PersonFaceInfomationTableService personFaceInfomationTableService;

    private PersonDataOperationTableService personDataOperationTableService;


    public StartThread(DrivePropertiesBean drivePropertiesBean, SubscriptionMapper subscriptionMapper, PersonTableService personTableService,
                       PersonFaceInfomationTableService personFaceInfomationTableService, PersonDataOperationTableService personDataOperationTableService) {
        this.drivePropertiesBean = drivePropertiesBean;
        this.subscriptionMapper = subscriptionMapper;
        this.personTableService = personTableService;
        this.personFaceInfomationTableService = personFaceInfomationTableService;
        this.personDataOperationTableService = personDataOperationTableService;
    }

    public void run() {
        try {
            System.out.println( "--------------开启守护线程,订阅保活--------------------" );
            //开启守护线程,订阅保活
            ContextLoaderListenerChildren.ThreadSubscriptionRefresh( drivePropertiesBean, subscriptionMapper );
            //开启守护线程,建立socket连接,监听端口号,获取数据
            System.out.println( "--------------开启守护线程,建立socket连接,监听端口号,获取数据--------------------" );
            ServerSocket serverSocket = new ServerSocket( Integer.parseInt( drivePropertiesBean.getServerSocketPort() ) );
            // 轮流等待请求
            while (true) {
                // 等待客户端请求,无请求则闲置;有请求到来时,返回一个对该请求的socket连接
                Socket clientSocket = serverSocket.accept();
                // 创建ThreadAlarm对象,通过socket连接通信
                Thread t = new Thread( new ThreadAlarm(drivePropertiesBean, clientSocket, personTableService,
                        personFaceInfomationTableService ,subscriptionMapper,personDataOperationTableService) );
                t.setDaemon( true );
                t.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
package com.test.service.websokctservice;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.test.config.CustomWebSocket;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Socket;
import java.nio.CharBuffer;
import java.util.Map;

/**
 * 实时获取订阅的消息推送到前端,渲染
 */
public class ThreadAlarm implements Runnable {
    private static final String SOAP_BEGIN = "{";
    private static final String SOAP_END = "}";
    private Socket socket;
    private String result = "";

    @Autowired
    private CustomWebSocket webSocketServlet;


    public ThreadAlarm(Socket socket) {
        this.socket = socket;
    }


    @Override
    public void run() {
        try {
            //输入流读取推送数据
            BufferedReader bufferedReader = new BufferedReader( new InputStreamReader( socket.getInputStream() ) );
            //创建缓存空间
            CharBuffer charbuffer = CharBuffer.allocate( 8192 );
            while ((bufferedReader.read( charbuffer )) != -1) {
                charbuffer.flip();//将Buffer从写模式切换到读模式
                result += charbuffer.toString();
            }
            System.out.println("———————————————监听获取数据成功——————————————result—————————————————————");
            //根据业务需求获取需要的数据
            if (result.indexOf( SOAP_BEGIN ) != -1 && result.indexOf( SOAP_END ) != -1) {
                String substring = result.substring( result.indexOf( SOAP_BEGIN ) );
                //解析json
                JSONObject jsonObject = JSONObject.parseObject( substring );
                //将json字符串转化成json对象
                JSONObject faceInfo = JSON.parseObject( json字符串 );
                Map rMap = (Map) JSON.parse( String.valueOf( ardInfo ) );
                String idImage = rMap.get( "IDImage" ).toString();
                //向前端页面发送消息
                 CustomWebSocket.sendInfo( 对象 );
                }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (socket != null) {
                try {
                    if (!socket.isClosed()) {
                        socket.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }

}

2.定时任务会默认创建线程池,项目关闭并不会关闭此线程池,

* 所以继承ContextLoaderListener类来关闭线程池

package com.bfdb.service.websokctservice;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.test.entity.SysServer;
import com.test.entity.websocket.*;
import com.test.mapper.SubscriptionMapper;
import com.test.untils.HttpResponseResult;
import com.test.untils.HttpUtil;
import org.springframework.web.context.ContextLoaderListener;

import javax.servlet.ServletContextEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 定时任务会默认创建线程池,项目关闭并不会关闭此线程池,
 * 所以继承ContextLoaderListener类来关闭线程池
 */
public class ContextLoaderListenerChildren extends ContextLoaderListener {
    private static ScheduledExecutorService executorService;

    public void contextInitialized(ServletContextEvent event) {
        super.contextInitialized( event );
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        //试图停止当前正执行的task,并返回尚未执行的task的list
        executorService.shutdownNow();
        super.contextDestroyed( event );
    }


    public static void ThreadSubscriptionRefresh(DrivePropertiesBean drivePropertiesBean, SubscriptionMapper subscriptionMapper) {
        executorService = Executors.newSingleThreadScheduledExecutor();
        //创建定时任务,定时刷新订阅
        executorService.scheduleAtFixedRate( new Runnable() {
            @Override
            public void run() {
                try {
                    List<LibID> libIDList=null;
                    LibID libID=null;
                    //获取服务器信息
                    List<SysServer> sysServerList = subscriptionMapper.getSysServerList();
                    //判断服务器信息
                    if (!"".equals(sysServerList) && sysServerList != null) {
                        for (SysServer sysServer : sysServerList) {
                            //判断服务器是否可连接
                            boolean hostReachable = HttpUtil.isHostReachable(sysServer.getServerIp(), 3);
                            Integer serverId = sysServer.getServerId();
                            //从数据库获取订阅信息
                            SysSubscriptionAlarm subscriptionAlarm = subscriptionMapper.getSubscription(serverId);
                            //如果能连接
                            if (hostReachable) {
                                String serverIP = sysServer.getServerIp();
                                String serverUsername = sysServer.getServerUsername();
                                String serverPwd = sysServer.getServerPwd();
                                if (subscriptionAlarm != null && !"".equals(subscriptionAlarm)) {
                                    //订阅信息实例化
                                    String subId = subscriptionAlarm.getSubId();
                                    //订阅刷新的有效时间
                                    Duration duration = new Duration();
                                    duration.setDuration( Integer.parseInt( drivePropertiesBean.getSubscriptionRefreshTime() ) );
                                    String durationString = JSON.toJSONString( duration );
                                    // 调用服务器刷新订阅接口
                                    HttpResponseResult httpResponseResult = HttpUtil.doPut( drivePropertiesBean.getSubscriptionUrlPre() +serverIP + drivePropertiesBean.getSubscriptionUrlAft()+subId, durationString, serverUsername, serverPwd );
                                    if (httpResponseResult != null) {
                                        //如刷新失败,则调用接口重新订阅
                                        if (httpResponseResult.getResponseCode() != 0) {
                                            //定义参数
                                            Subscription subscription = new Subscription();
                                            subscription.setAddressType(Integer.parseInt(drivePropertiesBean.getAddressType()));
                                            subscription.setIPAddress(drivePropertiesBean.getEquipmentIp());
                                            subscription.setPort(Integer.parseInt(drivePropertiesBean.getPort()));
                                            subscription.setType(Integer.parseInt(drivePropertiesBean.getSubscriptionType()));
                                            subscription.setDuration(Integer.parseInt( drivePropertiesBean.getSubscriptionInitTime() ) );
                                            subscription.setLibIDNum( Integer.parseInt( drivePropertiesBean.getSubscribePersonConditionLibIDNum() ) );
                                            //定义订阅的库 ID 列表
                                            libIDList=new ArrayList<>();
                                            //LibIDNum 为 0 时,此字段可选
                                            libID=new  LibID();
                                            libID.setId(3);
                                            libIDList.add(libID);
                                            subscription.setLibIDList(libIDList );
                                            //调用服务器订阅接口
                                            httpResponseResult = HttpUtil.doPost(drivePropertiesBean.getSubscriptionUrlPre() + serverIP + drivePropertiesBean.getSubscriptionUrlAft(),
                                                    JSONObject.toJSONString(subscription), serverUsername, serverPwd);
                                            if (httpResponseResult.getResponseCode() == 0) {
                                                //将订阅信息保存至数据库
                                                //获取返回订阅成功后返回的数据
                                                String subscriptionJson = httpResponseResult.getData();
                                                //进行json转换
                                                JSONObject jsonObject = JSONObject.parseObject( subscriptionJson );
                                                //从json字符串中获取返回的ID信息
                                                String jsonObjectString = jsonObject.getString( "ID" );
                                                //组成新的对象 报错到数据库中
                                                SysSubscriptionAlarm sysSubscriptionAlarm = new SysSubscriptionAlarm();
                                                //服务器id值
                                                sysSubscriptionAlarm.setSubscriptionalarmId(subscriptionAlarm.getSubscriptionalarmId());
                                                //订阅成功返回的订阅ID值
                                                sysSubscriptionAlarm.setSubId(jsonObjectString);
                                                //修改操作
                                                subscriptionMapper.updateSubScription(sysSubscriptionAlarm);
                                            }
                                        }
                                        System.out.println("---httpResponseResult----"+httpResponseResult);
                                    }
                                }

                            }
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, 0, Integer.parseInt( drivePropertiesBean.getUpdateSubscriptionTime() ) * 1000, TimeUnit.MILLISECONDS );
        /**
         *   command:执行线程
         initialDelay:初始化延时
         period:两次开始执行最小间隔时间
         unit:计时单位 (5000):5秒
         */
    }
}

3.前端和后端的交互的websocket

package com.test.config;

import com.alibaba.fastjson.JSONObject;
import com.test.entity.websocket.CardInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

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

/**
 * 前端和后端的交互的websocket
 * 这里@ServerEndpoint(value = "/websocket")的作用相当于端口号
 */
@Component
@ServerEndpoint("/websocket")
public class CustomWebSocket {

    /**
     * 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
     */
    private static int onlineCount = 0;

    /**
     * concurrent包的线程安全Set,用来存放每个客户端对应的CumWebSocket对象。
     */
    private static CopyOnWriteArraySet<CustomWebSocket> webSocketSet = new CopyOnWriteArraySet<CustomWebSocket>();

    /**
     * 通过session可以给每个WebSocket长连接中的客户端发送数据
     */
    private Session session;
    /**
     * 日志信息
     */
    private Logger log = LoggerFactory.getLogger( CustomWebSocket.class);

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        log.info("websocket客户端开启连接");
        this.session = session;
        webSocketSet.add(this);
        //添加在线人数
        addOnlineCount();
        log.info("新连接接入,当前在线人数为:" + getOnlineCount());
//        System.out.println(webSocketSet);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        log.info("websocket客户端关闭连接");
        //从set中删除
        webSocketSet.remove(this);
        //在线数减1
        subOnlineCount();
        log.info("有连接关闭。当前在线人数为:" + getOnlineCount());
    }
    /**
     * 收到客户端消息后调用的方法
     * @param message
     *            客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("用户发送过来的消息为:"+message);
    }

    /**
     * 发生错误时调用
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("websocket出现错误");
        error.printStackTrace();
    }
//    public void sendMessage(CardInfo message) {
//        try {
//            this.session.getBasicRemote().sendText(message);
//            log.info("推送消息成功,消息为:" + message);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }

    /**
     * 减少在线人数
     */
    private void subOnlineCount() {
        CustomWebSocket.onlineCount--;
    }

    /**
     * 添加在线人数
     */
    private void addOnlineCount() {
        CustomWebSocket.onlineCount++;
    }
    /**
     * 当前在线人数
     *
     * @return
     */
    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(CardInfo message) throws IOException {
        this.session.getBasicRemote().sendText( JSONObject.toJSONString(message));
    }

    /**
     * 自定义消息
     */
    public static void sendInfo(CardInfo message) throws IOException {
        for (CustomWebSocket productWebSocket : webSocketSet) {
            productWebSocket.sendMessage(message);
        }
    }

}

4.前端测试代码

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <!--<link rel="stylesheet" href="css/layui/css/layui.css">-->
    <!--<script src="css/layui/layui.js"></script>-->
    <link rel="stylesheet" th:href="@{/Content/Scripts/Master/layuiadmin/layui/css/layui.css}" media="all"/>
    <script th:src="@{/Content/Scripts/Master/layuiadmin/layui/layui.js}"></script>
    <link rel="stylesheet" th:href="@{/Content/Css/personverificationTerminal.css}" media="all"/>
    <script th:src="@{/Content/Scripts/Master/check_token.js}"></script>
    <style>
        .personal-prove{
            padding:15px;
            background-color: #f5f5f5;
        }
        .personal-prove .layui-card-header h3{
            font-weight: 800;
            font-size: 18px;
        }

        .div-lineheight{
            margin-bottom:10px;
        }
        .div-lineheight .layui-input-block{
            margin-left: 185px;
        }
        .div-lineheight .layui-form-label{
            width:155px;
        }
        .img-show{
            width: 125px;
            height: 160px;
        }
        .img-show img{
            width: 100%;
            height: 100%;
        }
        .load-group>div{
            margin-bottom: 20px;
        }
        .load-group .layui-form-label{
            width:100px;
        }
        .load-group .layui-input-block{
            margin-left: 130px;
        }
        .upload-card-img{
            float: left;
            margin-right: 10px;
        }
        .upload-card-img:last-child{
            margin-right: 0;
        }
        .upload-operate{
            width:210px;
            height: 138px;
            position: relative;
        }
        .upload-operate img{
            width: 100%;
            height: 100%;
        }
        .upload-operate input[type="file"]{
            width: 100%;
            height: 100%;
            position: absolute;
            left: 0;
            top: 0;
            opacity: 0;
        }
        .text-color-blue{
            width:210px;
            text-align: center;
            color:#20b6e9;
        }
        .upload {
            height: 160px;
            width: 100%;
            background-size: 30px;
            border: none;
            cursor: pointer;
            margin-top: -30px;
            margin-left: 2px;
        }
        .upLoadBox {
            margin-top: 0;
        }
        .layuiUploadImg {
            margin-top: -30px;
            width: 146px;
            height: 160px;
        }

    </style>
</head>
<body>
<div class="success-icon" style="display: none"><i class="layui-icon layui-icon-ok-circle"></i>
    <div style="font-size: 20px;color: green;margin-left: 20px" class="success-ok">提交成功!3秒后自动刷新</div>
</div>
<div id="PreviewImgAdd" onclick="closeAddImg();"
     style="
      position: fixed;
      z-index: 99;
      width: 100%;
      height: 100%;
      top: 0;
      display: none;

"
></div>
<div id="yincang" class="layui-fluid personal-prove layuinoMargin" style="display: block">
    <form class="layui-form" id="addStaff">
        <div class="layui-card">
            <div class="layui-card-header">
                <h3>基本信息</h3>
            </div>
            <div class="layui-card-body">
                <div class="layui-row layui-form">
                    <div class="layui-col-xs12 layui-col-sm6 layui-col-md4">
                        <div class="div-lineheight">
                            <label class="layui-form-label">采集设备名称:</label>
                            <div class="layui-input-block">
                                <select class="form-control" name="serverIds" id="serverIds">
                                    <option value="">请选择</option>
                                    <option th:each="sysServer:${sysServerListSuccess}"
                                            th:value="${sysServer.serverIp}"
                                            th:text="${sysServer.serverName}"></option>
                                </select>

                            </div>
                        </div>
                    </div>
                    <div class="layui-col-xs12 layui-col-sm6 layui-col-md4">
                        <div class="div-lineheight">
                            <div class="layui-form-label">姓名:</div>
                            <div class="layui-input-block">
                                <input type="text" name="personName" id="personName" lay-verify="title"
                                       class="layui-input" readonly>
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-xs12 layui-col-sm6 layui-col-md4">
                        <div class="div-lineheight">
                            <div class="layui-form-label">身份证号:</div>
                            <div class="layui-input-block">
                                <input type="text" name="identityNo" lay-verify="required" id="identityNo"
                                       class="layui-input" readonly>
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-xs12 layui-col-sm6 layui-col-md4">
                        <div class="div-lineheight">
                            <div class="layui-form-label">性别:</div>
                            <div class="layui-input-block">
                                <input type="radio" name="gender" value="1" id="gender1" title="男" readonly checked="">
                                <input type="radio" name="gender" value="0" id="gender2" title="女" readonly>
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-xs12 layui-col-sm6 layui-col-md4">
                        <div class="div-lineheight">
                            <div class="layui-form-label">人员类别:</div>
                            <div class="layui-input-block">
                                <!--                            <select></select>-->
                                <select class="form-control" name="identicationInfo" id="identicationInfo"
                                        lay-filter="projectfilter">
                                    <option value="">请选择</option>
                                    <option th:each="dataDictionary:${identicationInfoList}"
                                            th:value="${dataDictionary.dicCode}"
                                            th:text="${dataDictionary.dicName}"></option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-xs12 layui-col-sm6 layui-col-md4">
                        <div class="div-lineheight">
                            <div class="layui-form-label">出生年月:</div>
                            <div class="layui-input-block">
                                <input type="text" class="layui-input" name="birthday" id="birthday" readonly>
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-xs12 layui-col-sm12 layui-col-md12">
                        <div class="div-lineheight left-range">
                            <div class="layui-form-label">地址:</div>
                            <div class="layui-input-block">
                                <textarea name="residentialAddress" id="residentialaddre"
                                          class="layui-textarea layuClass" readonly></textarea>
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-xs12 layui-col-sm12 layui-col-md12">
                        <div class="div-lineheight left-range">
                            <div class="layui-form-label">备注:</div>
                            <div class="layui-input-block">
                                <textarea placeholder="请输入内容" name="description"
                                          class="layui-textarea layuClass"></textarea>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="layui-card">
            <div class="layui-card-header">
                <h3>照片上传</h3>
            </div>
            <div class="layui-card-body">
                <div class="layui-row load-group">
                    <div class="layui-col-md2">
                        <label class="layui-form-label">人脸照片:</label>
                        <div class="layui-input-block">
                            <div class="img-show" id="sonFiles">
                                <img src="/Content/Images/nopictures.png"  onclick="PreviewImg(this.src)">
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </form>
    <div class="layui-form-item">
        <div class="layui-input-block" style="text-align: center;margin:0 auto;">
            <button type="button" class="layui-btn" id="submitBtn">立即提交</button>
        </div>
    </div>
</div>



<script th:src="@{/Content/Scripts/Master/layuiadmin/layui/layui.js}"></script>
<script th:src="@{/Content/check/IDcardverification.js}"></script>
<script  type="text/javascript" th:inline="javascript">
    let basePath = [[${#httpServletRequest.getScheme() + "://" + #httpServletRequest.getServerName() + ":" + #httpServletRequest.getServerPort() + #httpServletRequest.getContextPath()}]];
    var access_token = window.localStorage.getItem("access_token"); //获取指定key本地存储的值
    layui.use(['form','laydate','upload', 'element', 'layer'],function(){
        var form=layui.form,
            laydate=layui.laydate;
        form.render();
        var $ = layui.jquery;
        var upload = layui.upload;
        var layer = layui.layer;
        //照片
        upload.render({
            elem: '#time',
            headers: {
                "access_token": access_token//此处放置请求到的用户token
            }
            , url: basePath + '/personTable/upload'
            , multiple: true
            , before: function (obj) {
                //预读本地文件示例,不支持ie8
                obj.preview(function (index, file, result) {
                    $('#cardEditImage').append('<div style="position: absolute;width: 124px; height: 159px">' +
                        '<img  src="' + result + '" alt="' + file.name + '" class="layuiUploadImg" onclick="PreviewImg(this.src)">' +
                        '<i class="layui-icon layui-icon-close"  onclick="deleteImg(this)" style="font-size: 30px;position: absolute;top:-30px;right:-16px;color: red">' +
                        '</i></div>')
                    $("#cardEditImage").find("i").each(function (i) {
                        $(this).attr("id", "deleteIcon" + i);
                    });
                    $("#cardEditImage").find("img").each(function (i) {
                        $(this).attr("id", "add_pic" + i);
                    });
                    $("#cardEditImage").append('<input type="hidden"  name="personFaceInfomationTableBean.campusCardAddress" value="' + result + '"/>');

                });
            }
            , done: function (res) {
            }
        });
        //重新加载
        layui.form.render("select");
        //获取项目的端口号
        //动态获取当前登录人的ip + 端口号
        var curWwwPath=document.location.host;
        var websocket = null;
        //判断当前浏览器是否支持WebSocket
        if ('WebSocket' in window) {
            //建立连接,这里的/websocket ,是Servlet中注解中的那个值
            //替换成自己的项目名
            // console.log("ws://" + curWwwPath + "/websocket");
            websocket = new WebSocket("ws://" + curWwwPath + "/websocket");
        } else {
            // alert('当前浏览器不支持websocket');
            layer.msg('当前浏览器不支持websocket', {time: 2000, icon: 5, offset: '250px'});//icon 1:对号2:x号 3:?号 4:锁号 5:哭脸 6:笑脸

        }
        //连接发生错误的回调方法
        websocket.onerror = function () {
            console.log("WebSocket连接发生错误");
            // layer.msg('WebSocket连接发生错误!!!', {time: 2000, icon: 5, offset: '250px'});//icon 1:对号2:x号 3:?号 4:锁号 5:哭脸 6:笑脸

        };
        //连接成功建立的回调方法
        websocket.onopen = function () {
            console.log("WebSocket连接成功");
            // layer.msg('WebSocket连接成功!!!', {time: 2000, icon: 6, offset: '250px'});//icon 1:对号2:x号 3:?号 4:锁号 5:哭脸 6:笑脸

        };

        //接收到消息的回调方法
        websocket.onmessage = function (event) {
            //可以在此处添加提示框和页面刷新
            var tar = event.data;
            //Json 对象转换为json字符串
            var jsonObj = JSON.parse(tar); //转换为json对象
        };
        //连接关闭的回调方法
        websocket.onclose = function () {
            console.log("WebSocket连接关闭");
            // layer.msg('WebSocket连接关闭!!!', {time: 1000, icon: 5, offset: '250px'});//icon 1:对号2:x号 3:?号 4:锁号 5:哭脸 6:笑脸

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

        //关闭WebSocket连接
        function closeWebSocket() {
            websocket.close();
        }
        //人证核验信息提交
        $("#submitBtn").click(function () {
        });

    })

    //关闭预览
    function closeAddImg() {
        $("#yincang").css('filter', '');
        $("#PreviewImgAdd").css("display","none");
    }


    //预览图片
    function PreviewImg(that) {
        let s = $("#PreviewImgAdd");
        s.show();
        $("#yincang").css('filter', 'blur(10px)');
        $("#PreviewImgAdd").css("display","block");
        $("#PreviewImgAdd").html("<img src="+that+" style='height: 500px;width: 30%;z-index: 150;margin-top: 200px;margin-left: 35%;'/>");

    }



    /**
     * 选择不同的采集设备
     * @param obj
     */
    function clickBtn(obj) {
        switch (obj.id) {
            case "confirm":
                // alert("确定");
                $("#cancel").removeClass('layui-btn-danger');
                $("#cancel").addClass('layui-btn-normal');
                $("#confirm").addClass('layui-btn-danger');
                document.getElementById("confirm").disabled = true;
                layui.use('form', function () {
                    var form = layui.form;
                    $('#serverIds').attr("disabled", "disabled");
                    form.render('select');
                });
                break;
            case "cancel":
                // alert("撤消");
                $("#cancel").addClass('layui-btn-danger');
                $("#confirm").removeClass('layui-btn-danger');
                $("#confirm").addClass('layui-btn-normal');
                document.getElementById("confirm").disabled = false;
                layui.use('form', function () {
                    var form = layui.form;
                    $('#serverIds').attr("disabled", false);
                    form.render('select');
                });
                break;
        }
    }
    function deleteImg(obj) {
        //删除图片展示上传按钮
        $(obj).parent("div").parent("div").find('button').show();
        $(obj).parent("div").next().remove();
        $(obj).parent("div").remove();
    }

</script>
</body>
</html>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
1. 添加依赖 首先,在 `pom.xml` 文件中添加 `spring-boot-starter-websocket` 依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> ``` 2. 配置WebSocket 在 `Application` 类中,添加 `@EnableWebSocket` 注解开启WebSocket支持,并实现 `WebSocketConfigurer` 接口: ``` @SpringBootApplication @EnableWebSocket public class Application implements WebSocketConfigurer { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(new WebSocketHandler(), "/chat").setAllowedOrigins("*"); } } ``` 这里创建了一个名为 `chat` 的WebSocket处理器,并指定允许所有来源的连接。 3. 编写WebSocketHandler 创建 `WebSocketHandler` 类,并实现 `WebSocketHandler` 接口: ``` public class WebSocketHandler implements org.springframework.web.socket.WebSocketHandler { private static final Logger logger = LoggerFactory.getLogger(WebSocketHandler.class); private final List<WebSocketSession> sessions = new CopyOnWriteArrayList<>(); @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { logger.info("New session connected: " + session.getId()); sessions.add(session); } @Override public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception { logger.info("Received message: " + message.getPayload()); for (WebSocketSession s : sessions) { s.sendMessage(message); } } @Override public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { logger.error("Error in transport", exception); } @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception { logger.info("Session closed: " + session.getId()); sessions.remove(session); } @Override public boolean supportsPartialMessages() { return false; } } ``` 这里定义了一个静态的 `sessions` 列表,用于保存所有连接的WebSocket会话。在 `afterConnectionEstablished` 方法中,将新建立的会话添加到 `sessions` 列表中。在 `handleMessage` 方法中,遍历所有WebSocket会话,将接收到的消息发送给所有客户端。 4. 编写前端页面 在 `resources/static` 目录下创建一个 `index.html` 文件,用于展示聊天室页面,并实现WebSocket的连接和发送消息功能: ``` <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>WebSocket Chat</title> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <script> var ws; function connect() { var username = $("#username").val(); if (!username) { alert("Please enter your username!"); return; } ws = new WebSocket("ws://" + location.host + "/chat"); ws.onopen = function(event) { console.log("WebSocket opened: " + event); ws.send(username + " joined the chat."); }; ws.onmessage = function(event) { console.log("WebSocket message received: " + event.data); $("#messages").append($("<li>").text(event.data)); }; ws.onerror = function(event) { console.error("WebSocket error: " + event); }; ws.onclose = function(event) { console.log("WebSocket closed: " + event); $("#messages").append($("<li>").text("WebSocket connection closed.")); }; } function send() { var message = $("#message").val(); if (!message) { alert("Please enter your message!"); return; } ws.send($("#username").val() + ": " + message); $("#message").val(""); } </script> </head> <body> <h1>WebSocket Chat</h1> <div> <label>Username:</label> <input type="text" id="username"> <button onclick="connect()">Connect</button> </div> <div> <label>Message:</label> <input type="text" id="message"> <button onclick="send()">Send</button> </div> <ul id="messages"></ul> </body> </html> ``` 在页面加载时,通过 `WebSocket` 构造函数创建一个WebSocket对象,并指定连接的URL。在连接建立后,通过 `send` 方法向服务器发送消息。在接收到消息时,在页面上显示消息内容。 5. 启动应用 最后,运行 `Application` 类的 `main` 方法启动应用。访问 `http://localhost:8080`,即可进入聊天室页面。输入用户名后点击 `Connect` 按钮连接WebSocket服务器,即可开始聊天。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

南大白

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值