IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 网络协议 -> 记录websocket以及线程池结合用的功能 -> 正文阅读

[网络协议]记录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>

  网络协议 最新文章
使用Easyswoole 搭建简单的Websoket服务
常见的数据通信方式有哪些?
Openssl 1024bit RSA算法---公私钥获取和处
HTTPS协议的密钥交换流程
《小白WEB安全入门》03. 漏洞篇
HttpRunner4.x 安装与使用
2021-07-04
手写RPC学习笔记
K8S高可用版本部署
mySQL计算IP地址范围
上一篇文章      下一篇文章      查看所有文章
加:2021-08-24 15:54:17  更:2021-08-24 15:56:18 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/25 21:52:10-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码