using System; using System.IO; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Threading; using System.Net.Sockets; using CardReaderService; using System.Net; using System.Diagnostics; using System.Text.RegularExpressions; namespace CardReaderService { public partial class CardReaderService : Form { public CardReaderService() { InitializeComponent(); Control.CheckForIllegalCrossThreadCalls = false; } //自动监听标志 public bool setListenAutoStart; //读卡器端口 public int ListenPortForIdCard; //就诊卡端口 public int ListenPortForVcCard; //身份证设备类型 public int deviceTypeForIdCard; //就诊卡设备类型 public int deviceTypeForVcCard; /// /// 程序入口 /// /// /// private void CardReaderService_Load(object sender, EventArgs e) { //开始Load设置信息 this.load_default_configs(); notifyCardReaderIcon.Visible = false; //托盘图标可见 notifyCardReaderIcon.Text = String.Format("{0} V1.0", Properties.Settings.Default.FormTitle); this.ShowInTaskbar = true; //不显示在系统任务栏 //窗口标题初始化 this.Text = String.Format("{0} By Mr.Zr", Properties.Settings.Default.FormTitle); //开始侦听 this.startServer(); //最小化窗口 this.WindowState = FormWindowState.Minimized; this.Hide(); } /// /// 窗口初始化时载入配置文件默认设置 /// private void load_default_configs() { //端口监听控件部分开始 //自动监听标志 this.setListenAutoStart = Properties.Settings.Default.ListenAutoStart; //监听端口 this.ListenPortForVcCard = Properties.Settings.Default.ListenPortForVcCard; this.ListenPortForIdCard = Properties.Settings.Default.ListenPortForIdCard; //设备类型 this.deviceTypeForIdCard = Properties.Settings.Default.DeviceTypeForIdCard; this.deviceTypeForVcCard = Properties.Settings.Default.DeviceTypeForVcCard; } /// /// 弹出小提示框 /// /// 标题 /// 内容 /// 显示时间MS毫秒 /// 小图标 0 Info 1 Error 2 Warinig Other None private void showToolTip(string showTitle, string showInfo, int showTime = 1000, int icon = 0) { ToolTipIcon iconType = new ToolTipIcon(); iconType = ToolTipIcon.None; switch (icon) { case 0: iconType = ToolTipIcon.Info; break; case 1: iconType = ToolTipIcon.Error; break; case 2: iconType = ToolTipIcon.Warning; break; default: iconType = ToolTipIcon.None; break; } this.notifyCardReaderIcon.ShowBalloonTip(showTime, showTitle, showInfo, iconType);//显示小窗口 } /// /// 劫持关闭-》最小化到托盘 /// /// /// private void CardReaderService_FormClosing(object sender, FormClosingEventArgs e) { e.Cancel = true; this.WindowState = FormWindowState.Minimized; this.Hide(); //this.ShowInTaskbar = false; this.notifyCardReaderIcon.Visible = true; } /// /// 最小化时托盘图标显示 /// /// /// private void CardReaderService_SizeChanged(object sender, EventArgs e) { if (this.WindowState == FormWindowState.Minimized) { this.Hide(); //this.ShowInTaskbar = false; this.notifyCardReaderIcon.Visible = true; } } /// /// 托盘图标双击显示窗口 /// /// /// private void notifyCardReaderIcon_MouseDoubleClick(object sender, MouseEventArgs e) { if (this.WindowState == FormWindowState.Minimized) { this.Show(); this.WindowState = FormWindowState.Normal; notifyCardReaderIcon.Visible = false; this.ShowInTaskbar = true; } } /// /// 推出程序释放资源 /// private void ExitMainForm() { if (MessageBox.Show("您确定要退出读卡服务程序吗?", "确认退出", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK) { this.notifyCardReaderIcon.Visible = false; this.Close(); this.Dispose(); Application.Exit(); } } /// /// 推出程序释放资源 /// public void exit() { this.notifyCardReaderIcon.Visible = false; this.Close(); this.Dispose(); Environment.Exit(0); } /// /// 右键菜单点击关闭窗口 /// /// /// private void 退出程序ToolStripMenuItem_Click(object sender, EventArgs e) { this.ExitMainForm(); } /////套接字部分////// Thread threadWatchForIdCard = null; //负责监听客户端的线程 Socket socketWatchForIdCard = null; //负责监听客户端的套接字 Socket socConnectionForIdCard = null; //创建一个负责和客户端通信的套接字 Thread threadWatchForVcCard = null; //负责监听客户端的线程 Socket socketWatchForVcCard = null; //负责监听客户端的套接字 Socket socConnectionForVcCard = null; //创建一个负责和客户端通信的套接字 /// /// 身份证监听客户端发来的请求 /// private void WatchConnectingForIdCardNo() { while (true) { try { socConnectionForIdCard = socketWatchForIdCard.Accept(); string remoteaddr = socConnectionForIdCard.RemoteEndPoint.ToString(); //将输入的字符串转换成 机器可以识别的字节数组 byte[] msg = Encoding.UTF8.GetBytes("connect"); //创建一个通信线程 ParameterizedThreadStart pts = new ParameterizedThreadStart(ServerRecMsg); Thread thr = new Thread(pts); thr.IsBackground = true; //启动线程 thr.Start(new object[2]{socConnectionForIdCard, "idCard"}); } catch (Exception e) { txtMsg.AppendText("启动身份证监听线程失败(WatchConnecting):" + GetCurrentTime() + "\r\n" + e.Message.ToString() + "\r\n"); //break; } } } /// /// 就诊卡监听客户端发来的请求 /// private void WatchConnectingForVcCardNo() { while (true) { try { socConnectionForVcCard = socketWatchForVcCard.Accept(); string remoteaddr = socConnectionForVcCard.RemoteEndPoint.ToString(); //将输入的字符串转换成 机器可以识别的字节数组 byte[] msg = Encoding.UTF8.GetBytes("connect"); //创建一个通信线程 ParameterizedThreadStart pts = new ParameterizedThreadStart(ServerRecMsg); Thread thr = new Thread(pts); thr.IsBackground = true; //启动线程 thr.Start(new object[2]{socConnectionForVcCard,"vcCard"}); } catch (Exception e) { txtMsg.AppendText("启动就诊卡线程失败(WatchConnecting):" + GetCurrentTime() + "\r\n" + e.Message.ToString() + "\r\n"); //break; } } } /// /// 接收客户端发来的信息 /// /// 客户端套接字对象 private void ServerRecMsg(object socketClientPara) { var arr = (object[])socketClientPara; Socket socketServer = arr[0] as Socket; try { //创建一个内存缓冲区 其大小为1024*3字节 即3kb byte[] arrServerRecMsg = new byte[1024 * 3]; //将接收到的信息存入到内存缓冲区,并返回其字节数组的长度 int length = socketServer.Receive(arrServerRecMsg); string type = arr[1] as string; string requestHeader = Encoding.UTF8.GetString(arrServerRecMsg); //获取请求文件及路径 Regex reg = new Regex("GET (.+) HTTP"); Match m = reg.Match(requestHeader); //如果是文件请求则直接返回 if (m.ToString() != "GET / HTTP") { socketServer.Close(); return; } try { //将输入的字符串转换成 机器可以识别的字节数组 string response = "", responseContent = ""; Console.WriteLine(type); if(type == "idCard") { responseContent = this.ReadIdCard(); } else if(type == "vcCard") { responseContent = this.ReadVcCard(); } txtMsg.AppendText("ServerRecMsg:" + GetCurrentTime() + "\r\n" + responseContent + "\r\n"); response += "HTTP/1.1 200 OK \r\n"; response += "Access-Control-Allow-Origin:* \r\n"; response += "Access-Control-Allow-Methods: GET, POST, OPTIONS \r\n"; response += "Content-Type: application/json; charset=UTF-8"; response += "\r\n\r\n"; response += responseContent; byte[] msg = Encoding.UTF8.GetBytes(response); //向客户端发送字节数组信息 socketServer.Send(msg); socketServer.Close(); } catch (Exception e) { Console.WriteLine(e); txtMsg.AppendText("读卡错误(ServerRecMsg):" + GetCurrentTime() + "\r\n" + e.Message.ToString() + "\r\n"); } } catch (Exception e) { Console.WriteLine(e); txtMsg.AppendText("远程连接错误(ServerRecMsg):" + GetCurrentTime() + "\r\n" + e.Message.ToString() + "\r\n"); } } /// /// 读就诊卡方法 /// /// /// private string ReadVcCard() { string result = "-1"; Dk_Reader.Reader reader = new Dk_Reader.Reader(); switch(this.deviceTypeForVcCard) { case 1 : //深圳市德卡科技股份有限公司 D8 result = reader.Get_d8CardNo(); break; case 2 : //天津环球磁卡股份有限公司 GMCC-DC001 result = reader.Get_CMCCDC001CardNo(); break; case 3: //华大读卡器HD-100 result = reader.Get_HuaDaHd_100(); break; case 4 : //深圳市德卡科技股份有限公司 D3 result = reader.Get_d3CardNo(); break; case 5 : //华大读卡器HD-100 南丘县人民医院 result = reader.Get_HuaDaHd_100_2(); break; case 6: //深圳市明泰智能技术有限公司-URF-R330 邢台市巨鹿医院 result = reader.getVcCardURF_R330(); break; case 7: // 深圳市明华奥汉科技股份有限公司-URF-35LT-N ---承德市妇幼保健院 result = reader.getVcCardURF_R35LT(); break; case 8: // GWI-IC30A 滦平县妇幼保健院 result = reader.getVcCardGWI_IC30A(); break; } return result; } /// /// 读身份证方法 /// /// private string ReadIdCard() { string result = "{code:-1}"; Dk_Reader.Reader reader = new Dk_Reader.Reader(); switch(this.deviceTypeForIdCard) { case 1 : //华视身份证读卡器CVR-100UC //北京金诚信齐通科技有限公司 型号号GHC860 result = reader.Get_HuaShiCardNo(); break; case 2: //威海新北洋数码有限公司 by618-108 result = reader.getIdCard_by618108(); break; } return result; } /// /// 获取当前系统时间的方法 /// /// 当前时间 private DateTime GetCurrentTime() { DateTime currentTime = new DateTime(); currentTime = DateTime.Now; return currentTime; } /// /// 启动监听服务 /// private void startServer() { try { //启动身份证读卡监听 //定义一个套接字用于监听客户端发来的信息 包含3个参数(IP4寻址协议,流式连接,TCP协议) socketWatchForIdCard = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //服务端发送信息 需要1个IP地址和端口号 //IPAddress ipaddress = IPAddress.Parse(txtIP.Text.Trim()); //获取文本框输入的IP地址 //将IP地址和端口号绑定到网络节点endpoint上 IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, this.ListenPortForIdCard); //获取文本框上输入的端口号 //监听绑定的网络节点 socketWatchForIdCard.Bind(endpoint); //将套接字的监听队列长度限制为20 socketWatchForIdCard.Listen(20); //创建一个监听线程 threadWatchForIdCard = new Thread(WatchConnectingForIdCardNo); //将窗体线程设置为与后台同步 threadWatchForIdCard.IsBackground = true; //启动线程 threadWatchForIdCard.Start(); //启动就诊卡读卡监听 //定义一个套接字用于监听客户端发来的信息 包含3个参数(IP4寻址协议,流式连接,TCP协议) socketWatchForVcCard = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //服务端发送信息 需要1个IP地址和端口号 IPEndPoint endpoint2 = new IPEndPoint(IPAddress.Any, this.ListenPortForVcCard); //获取文本框上输入的端口号 //监听绑定的网络节点 socketWatchForVcCard.Bind(endpoint2); //将套接字的监听队列长度限制为20 socketWatchForVcCard.Listen(20); //创建一个监听线程 threadWatchForVcCard = new Thread(WatchConnectingForVcCardNo); //将窗体线程设置为与后台同步 threadWatchForVcCard.IsBackground = true; //启动线程 threadWatchForVcCard.Start(); //启动线程后 txtMsg文本框显示相应提示 txtMsg.AppendText("开始监听客户端传来的信息!" + "\r\n"); } catch (Exception e) { txtMsg.AppendText(String.Format("启动服务失败(startServer):{0}!" + "\r\n", e.Message.ToString())); } } /////套接字结束////// private void btnStartListen_Click(object sender, EventArgs e) { this.startServer(); } } }