Asp. net MVC 는 모든 브 라 우 저 플러그 인 이 WebSocket 기술 을 사용 할 수 있 도록 신분증 정 보 를 읽 습 니 다.

1. 사고방식: 브 라 우 저 를 사용 하 는 컴퓨터 에 웹 소켓 서버 를 설치한다.브 라 우 저의 동작 알림 을 읽 어 서버 에 알 리 고 서버 에서 신분증 읽 기 메커니즘 을 터치 합 니 다.
2. 서버 에서 브 라 우 저 에 알림 을 처리 하면 모든 브 라 우 저가 신분증 을 읽 을 수 있 습 니 다.
구체 적 인 코드 는 다음 과 같다.
브 라 우 저 쪽:

 $(function () {
        try {
              openReader();
            } catch (e) 
            { 
            }
  });
 function openReader() {
            var host = "ws://127.0.0.1:8888";
            if (socket == null) {
                resultMsg("      .");
                socket = new WebSocket(host);
            } else {
                resultMsg("     .");
            }
            try {
                socket.onopen = function (msg) {
                    clearZP(); //  zp         
                };
                socket.onerror = function () {
                    sendFlag = -1;
                    resultMsg("     ");
                };
                socket.onmessage = function (msg) {
                    if (typeof msg.data == "string") {
                        var msgM = msg.data + "";

                        if (msgM[0] == "0") {
                            resultMsg("        ,      .");
                        } else if (msgM[0] == "3") {
                            alert("     .");
                        } else if (msgM[0] == "4") {
                            alert("     .");
                        } else if (msgM[0] == "5") {
                            alert("         ,         .");
                        } else {
                            //      
                            //document.getElementById("text_ID").value= msgM.match(/identityCardID(\S*)identityCardID/)[1];   //  ID
                            document.all['id'].value = msgM.split('|')[0];   //      
                            //document.getElementById("text_sex").value = msgM.match(/sex(\S*)sex/)[1];   //               
                            // document.getElementById("text_nation").value = msgM.match(/nation(\S*)nation/)[1];     //                        
                            //document.getElementById("text_birthday").value = msgM.match(/birthDate(\S*)birthDate/)[1];       //                      
                            // document.getElementById("text_address").value = msgM.match(/address(\S*)address/)[1];          //    
                            document.all['id'].value = msgM.split('|')[1];         //          
                            //document.getElementById("text_dept").value = msgM.match(/issuingAuthority(\S*)issuingAuthority/)[1];  //                             
                            // document.getElementById("text_effDate").value = msgM.match(/beginPeriodOfValidity(\S*)beginPeriodOfValidity/)[1];       //                         
                            // document.getElementById("text_expDate").value = msgM.match(/endPeriodOfValidity(\S*)endPeriodOfValidity/)[1];        //      
                            // document.all("PhotoID").src = "data:image/jpeg;base64," + msgM.match(/##(\S*)##/)[1];//    
                        }

                    };
                }
            }
            catch (ex) {
                alert("    ,           .");
            }
        }
        function resultMsg(msg) {
            console.log("\r
" + msg); } // BMP function clearZP() { sendFlag = 1; socket.send("SDT_ClearZP#"); // //socket.send("SDT_ReadCard#"); } // function openReaderStart() { sendFlag = 2; socket.send("SDT_OpenReader#"); } // function readIDCard() { if (sendFlag == -1) { alert(" "); } else { try { socket.send("SDT_ReadCard#"); // BMP socket.send //socket.send("SDT_ReadCard#"); BMP socket.send } catch (ex) { resultMsg(" ."); } } } // function closeReader() { sendFlag = 4; try { socket.send("SDT_CloseReader#"); } catch (ex) { resultMsg(" ."); } } function closeSocket() { try { if (socket != null) { socket.close(); socket = null; } } catch (ex) { } };

서버 코드 는 다음 과 같 습 니 다.
1. windows 서 비 스 를 하려 면 Topshelf 를 설치 해 야 하기 때 문 입 니 다.
2. 웹 소켓 을 만 들 려 면 nuget 패키지 Fleck 이 필요 하기 때문에 왜 이 가방 을 선 택 했 습 니까? 이 웹 소켓 이 오류 가 발생 하면 스스로 다시 시작 할 수 있 기 때 문 입 니 다.
3. 콘 솔 프로그램 Program. cs 코드 는 다음 과 같 습 니 다.
using Fleck;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Topshelf;

namespace IDCardReader
{
    class Program
    {
        private static NLog.Logger logger = NLog.LogManager.GetLogger("websocketserver");
        static void Main(string[] args)
        {
            try
            {
                var rc = HostFactory.Run(x =>
                {
                    x.Service(s =>
                    {
                        s.ConstructUsing(name => new Program());
                        s.WhenStarted(p => p.Start());
                        s.WhenStopped(p => p.Stop());
                    });
                    x.RunAsLocalSystem();

                    x.SetServiceName("MyShenIDCardServices");
                    x.SetDisplayName("        ");
                });

                var exitCode = (int)Convert.ChangeType(rc, rc.GetTypeCode());
                Environment.ExitCode = exitCode;
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
            }
        }

        /// 
        ///     
        /// 
        void Start()
        {
            try
            {
                Task.Run(() =>
                {
                    var allSockets = new List();
                    var server = new WebSocketServer("ws://0.0.0.0:" + 8888");
                    //       
                    server.RestartAfterListenError = true;
                    server.Start(socket =>
                    {
                        socket.OnOpen = () =>
                        {
                            string IpAddress = socket.ConnectionInfo.ClientIpAddress;
                            int Port = socket.ConnectionInfo.ClientPort;
                            allSockets.Add(socket);
                            Console.WriteLine("\r
" + System.DateTime.Now + " [ \"" + IpAddress + ":" + Port + "\" ! :" + allSockets.Count + "]"); }; socket.OnClose = () => { string IpAddress = socket.ConnectionInfo.ClientIpAddress; int Port = socket.ConnectionInfo.ClientPort; allSockets.Remove(socket); Console.WriteLine("\r
" + System.DateTime.Now + " [ \"" + IpAddress + ":" + Port + "\" ! :" + allSockets.Count + "]"); }; socket.OnMessage = message => { string IpAddress = socket.ConnectionInfo.ClientIpAddress; int Port = socket.ConnectionInfo.ClientPort; Console.WriteLine("\r
" + System.DateTime.Now + " [ \"" + IpAddress + ":" + Port + " : " + message); switch (message) { //case "SDT_ClearZP#": // allSockets.ToList().ForEach(s => // { // if (s == socket) // { // s.Send("123"); // } // }); // break; //case "SDT_OpenReader#": // // HuaShiIDCardReader.OpenReader(); // allSockets.ToList().ForEach(s => // { // if (s == socket) // { // s.Send("1"); // } // }); // break; case "SDT_ReadCard#": // allSockets.ToList().ForEach( s => { if (s == socket) { s.Send(HuaShiIDCardReader.ReadCard()); } }); string path = System.AppDomain.CurrentDomain.BaseDirectory; File.Delete(path + "wz.txt"); File.Delete(path + "zp.bmp"); break; default: break; } }; socket.OnError = error => { string IpAddress = socket.ConnectionInfo.ClientIpAddress; int Port = socket.ConnectionInfo.ClientPort; allSockets.Remove(socket); Console.WriteLine("\r
" + System.DateTime.Now + " [ \"" + IpAddress + ":" + Port + "\" ! :" + allSockets.Count + "]"); }; }); }); } catch (Exception ex) { logger.Error(ex.Message); } } /// /// /// void Stop() { logger.Error(" "); } } }

4. 도 킹 은 중국 시각 판독 기 HuaShiIDCardReader. cs 입 니 다.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace IDCardReader
{
    public class HuaShiIDCardReader
    {
        //   

        static int iRetUSB = 0;

        public static void OpenReader()
        {
            try
            {
                if(iRetUSB!=1)
                {
                    int iPort = 0;
                    for (iPort = 1001; iPort <= 1016; iPort++)
                    {
                        iRetUSB = CVRSDK.CVR_InitComm(iPort);
                        if (iRetUSB == 1)
                        {
                            break;
                        }
                    }
                }
               
            }
            catch (Exception)
            {
                
            }
        }

        //public static string ReadCard()
        //{
        //    try
        //    {
               

        //        if (iRetUSB == 1)
        //        {
        //            this.labelOpResult.Text = "     !";
        //        }
        //        else
        //        {
        //            this.labelOpResult.Text = "     !";
        //        }

        //        int authenticate = CVRSDK.CVR_Authenticate();
        //        if (authenticate == 1)
        //        {
        //            int readContent = CVRSDK.CVR_Read_FPContent();
        //            if (readContent == 1)
        //            {
        //                this.labelOpResult.Text = "      !";
        //                FillData();
        //            }
        //            else
        //            {
        //                this.labelOpResult.Text = "      !";
        //            }
        //        }
        //        else
        //        {
        //            MessageBox.Show("           ");
        //        }
        //        CVRSDK.CVR_CloseComm();
        //    }
        //    catch (Exception ex)
        //    {
        //        MessageBox.Show(ex.ToString());
        //    }

        //    string msg = "";
        //    try
        //    {
               
        //        if (iRetUSB == 1)
        //        {
        //            msg = getUserInfo().ToString();//     
        //        }
        //        else
        //        {
        //            msg = "5";// "     !";
        //        }
               
        //    }
        //    catch (Exception ex)
        //    {
                
        //    }
        //    return msg;
        //}
        public static string ReadCard()
        {
            string name = "";
            try
            {
                int iPort, iRetUSB = 0;
                for (iPort = 1001; iPort <= 1016; iPort++)
                {
                    iRetUSB = CVRSDK.CVR_InitComm(iPort);
                    if (iRetUSB == 1)
                    {
                        break;
                    }
                }
                if (iRetUSB != 1)
                {
                    return "3";
                }
                int authenticate = CVRSDK.CVR_Authenticate();
                if (authenticate == 1) 
                {
                    int readContent = CVRSDK.CVR_Read_FPContent();

                    if (readContent == 1)
                    {
                        byte[] Sname = new byte[30];
                        int length = 30;
                        CVRSDK.GetPeopleName(ref Sname[0], ref length);
                        //MessageBox.Show();
                        byte[] number = new byte[36];
                        length = 36;
                        CVRSDK.GetPeopleIDCode(ref number[0], ref length);

                        name = System.Text.Encoding.GetEncoding("GB2312").GetString(Sname).Replace("\0", "").Trim() + "|" +
                        System.Text.Encoding.GetEncoding("GB2312").GetString(number).Replace("\0", "").Trim();
                    }
                    else
                    {
                        name = "5";//"      !";
                    }
                }
                else
                {
                    name = "4";//name="           ";
                }
            }
            catch (Exception ex)
            {
                name = "0";
            }
            finally
            {
                CloseCard();
            }
            return name;
        }

        private static void CloseCard()
        {
            int C = CVRSDK.CVR_CloseComm();
        }
    }
}

4. 도입 dll 류 파일 읽 기, CVRSDK. cs
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Runtime.InteropServices;//    DllImport       

namespace IDCardReader
{
    /// 
    ///       
    /// 
    class CVRSDK
    {
        [DllImport("Termb.dll", EntryPoint = "CVR_InitComm", CharSet = CharSet.Ansi, SetLastError = false)]
        public static extern int CVR_InitComm(int Port);//          ,  Win32API    


        [DllImport("Termb.dll", EntryPoint = "CVR_Authenticate", CharSet = CharSet.Ansi, SetLastError = false)]
        public static extern int CVR_Authenticate();


        [DllImport("Termb.dll", EntryPoint = "CVR_Read_Content", CharSet = CharSet.Ansi, SetLastError = false)]
        public static extern int CVR_Read_Content(int Active);


        [DllImport("Termb.dll", EntryPoint = "CVR_Read_FPContent", CharSet = CharSet.Ansi, SetLastError = false)]
        public static extern int CVR_Read_FPContent();

        [DllImport("Termb.dll", EntryPoint = "CVR_FindCard", CharSet = CharSet.Ansi, SetLastError = false)]
        public static extern int CVR_FindCard();

        [DllImport("Termb.dll", EntryPoint = "CVR_SelectCard", CharSet = CharSet.Ansi, SetLastError = false)]
        public static extern int CVR_SelectCard();


        [DllImport("Termb.dll", EntryPoint = "CVR_CloseComm", CharSet = CharSet.Ansi, SetLastError = false)]
        public static extern int CVR_CloseComm();

        [DllImport("Termb.dll", EntryPoint = "GetCertType", CharSet = CharSet.Ansi, SetLastError = false)]
        public static extern unsafe int GetCertType(ref byte strTmp, ref int strLen);


        [DllImport("Termb.dll", EntryPoint = "GetPeopleName", CharSet = CharSet.Ansi, SetLastError = false)]
        public static extern unsafe int GetPeopleName(ref byte strTmp, ref int strLen);


        [DllImport("Termb.dll", EntryPoint = "GetPeopleChineseName", CharSet = CharSet.Ansi, SetLastError = false)]
        public static extern unsafe int GetPeopleChineseName(ref byte strTmp, ref int strLen);


        [DllImport("Termb.dll", EntryPoint = "GetPeopleNation", CharSet = CharSet.Ansi, SetLastError = false)]
        public static extern int GetPeopleNation(ref byte strTmp, ref int strLen);


        [DllImport("Termb.dll", EntryPoint = "GetNationCode", CharSet = CharSet.Ansi, SetLastError = false)]
        public static extern int GetNationCode(ref byte strTmp, ref int strLen);


        [DllImport("Termb.dll", EntryPoint = "GetPeopleBirthday", CharSet = CharSet.Ansi, SetLastError = false, CallingConvention = CallingConvention.StdCall)]
        public static extern int GetPeopleBirthday(ref byte strTmp, ref int strLen);


        [DllImport("Termb.dll", EntryPoint = "GetPeopleAddress", CharSet = CharSet.Ansi, SetLastError = false, CallingConvention = CallingConvention.StdCall)]
        public static extern int GetPeopleAddress(ref byte strTmp, ref int strLen);


        [DllImport("Termb.dll", EntryPoint = "GetPeopleIDCode", CharSet = CharSet.Ansi, SetLastError = false, CallingConvention = CallingConvention.StdCall)]
        public static extern int GetPeopleIDCode(ref byte strTmp, ref int strLen);


        [DllImport("Termb.dll", EntryPoint = "GetDepartment", CharSet = CharSet.Ansi, SetLastError = false, CallingConvention = CallingConvention.StdCall)]
        public static extern int GetDepartment(ref byte strTmp, ref int strLen);


        [DllImport("Termb.dll", EntryPoint = "GetStartDate", CharSet = CharSet.Ansi, SetLastError = false, CallingConvention = CallingConvention.StdCall)]
        public static extern int GetStartDate(ref byte strTmp, ref int strLen);


        [DllImport("Termb.dll", EntryPoint = "GetEndDate", CharSet = CharSet.Ansi, SetLastError = false, CallingConvention = CallingConvention.StdCall)]
        public static extern int GetEndDate(ref byte strTmp, ref int strLen);


        [DllImport("Termb.dll", EntryPoint = "GetPeopleSex", CharSet = CharSet.Ansi, SetLastError = false, CallingConvention = CallingConvention.StdCall)]
        public static extern int GetPeopleSex(ref byte strTmp, ref int strLen);


        [DllImport("Termb.dll", EntryPoint = "CVR_GetSAMID", CharSet = CharSet.Ansi, SetLastError = false, CallingConvention = CallingConvention.StdCall)]
        public static extern int CVR_GetSAMID(ref byte strTmp);

        [DllImport("Termb.dll", EntryPoint = "GetBMPData", CharSet = CharSet.Ansi, SetLastError = false, CallingConvention = CallingConvention.StdCall)]
        public static extern int GetBMPData(ref byte btBmp, ref int nLen);

        [DllImport("Termb.dll", EntryPoint = "GetJpgData", CharSet = CharSet.Ansi, SetLastError = false, CallingConvention = CallingConvention.StdCall)]
        public static extern int GetJpgData(ref byte btBmp, ref int nLen);

    }

}

원본 주소:https://download.csdn.net/download/IT_ziliang/12477569

좋은 웹페이지 즐겨찾기