public void start(IPEndPoint point) { try { this.listenSocket = new Socket(point.AddressFamily, SocketType.Stream, ProtocolType.Tcp); listenSocket.Bind(point); listenSocket.Listen(numConnections); if (SysCache.ShowInfoLog) { LogHelper.Info("WEB通信服务已经开启!!"); ShowLogData.add("WEB通信服务已经开启!!"); } startAccept(null); } catch (Exception e) { if (SysCache.ShowErrorLog) { string error = string.Format("启动WEB服务器{0}出错,错误信息为{1}", point.ToString(), e.Message); LogHelper.Error(error); } string msg = string.Format("服务程序启动失败,端口号{0}被占用,程序退出!", point.Port); if (onServerStartHandler != null) { onServerStartHandler(this, msg); } } }
//监听启动,以下为数据服务内容2015-12-17理解zlc public void start(IPEndPoint point)//any的IP地址+用户在xml中设置的PORT { try { this.listenSocket = new Socket(point.AddressFamily, SocketType.Stream, ProtocolType.Tcp); listenSocket.Bind(point); listenSocket.Listen(numConnections); if (SysCache.ShowInfoLog) { LogHelper.Info("DTU通信服务已经开启!!"); ShowLogData.add("DTU通信服务已经开启!!"); } //开启守护进程 deamonThread = new DeamonThread(this, timeout); startAccept(null); } catch (Exception e) { if (SysCache.ShowErrorLog) { string error = string.Format("启动DTU服务器{0}出错,错误信息为{1}", point.ToString(), e.Message); LogHelper.Error(error); } string msg = string.Format("服务程序启动失败,端口号{0}被占用,程序已经启动正在运行!", point.Port); if (onServerConnectedHandler != null) { onServerConnectedHandler(this, msg); } } }
public override bool processCommand(DTU.GateWay.Protocol.Command command) { string receive = HexStringUtility.ByteArrayToHexString(command.Data); LogHelper.Info("收到的数据为:[" + userToken.ConnectedSocket.RemoteEndPoint.ToString() + "]" + receive); ShowLogData.add(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":[" + userToken.ConnectedSocket.RemoteEndPoint.ToString() + "]" + receive); byte[] data = HexStringUtility.HexStringToByteArray(receive); //data[data.Length - 1] = FormatHelper.CheckSum(data, 0, data.Length - 1); send(data, 0, data.Length); return(true); }
/// <summary> /// 时钟,用来更显下边栏状态 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void toolTripTime_Tick(object sender, EventArgs e) { setUpTime();// 更新时间显示 //if (DataSynLib.DataSyn.isRun) 数据同步ToolStripMenuItem.ForeColor = System.Drawing.Color.Green; //else 数据同步ToolStripMenuItem.ForeColor = System.Drawing.Color.Red; if (!isRefresh) { isRefresh = true; /* * if (dtuServer != null) * { * int count = dtuServer.AsyncSocketUserTokenList.count();//计算socket连接数量 * //this.connectedStripStatusLabel.Text = count.ToString();//显示在线设备数量 * } */ this.connectedStripStatusLabel.Text = OnlineDeviceService.GetOnlineCount().ToString();//显示在线设备数量 DateTime dateNow = DateTime.Now; if (!ToDtuCommand.isClear && ToDtuCommand.dateNew < dateNow.AddHours(-2)) { ShowLogData.add("【" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "】清理ToDtuCommand信息"); ToDtuCommand.Clear(); } if (!ToWaterDtuCommand.isClear && ToWaterDtuCommand.dateNew < dateNow.AddHours(-2)) { ShowLogData.add("【" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "】清理ToWaterDtuCommand信息"); ToWaterDtuCommand.Clear(); } /* * timeCount = timeCount + 1; * if (this.timeCount == 5)//5秒初始化一次大表格 * { * this.timeCount = 0; * lock (this.deviceListsDataGridView) * { * initDataGridView(); * } * } * */ isRefresh = false; } }
//启动时,设备全部显示离线 #region 2015-8-7 每次启动时,将登陆状态置为0 void installDeviceState() { try { BaseModule.LoadBaseInfo(); CardUserModule.LoadCardUsers(); DistrictModule.UpdateLevelInfo(); DistrictModule.UpdateDistrictInfo(); //将在线状态置为0 DeviceModule.SetOnline0(); DeviceModule.LoadDevices(); /* * IList<Device> deviceList = DeviceModule.GetAllDevice(); * * foreach (Device d in deviceList) * { * if (d.Online == 1) * { * d.Online = 0; * DeviceModule.ModifyDevice(d); * } * } * */ AlarmService.Init(); int alarmCount = AlarmService.GetCount(); //logHelper.Info("程序启动报警数量为:" + alarmCount); ShowLogData.add("程序启动报警数量为:" + alarmCount); } catch (Exception e) { if (showErrorLog) { string error = string.Format("在将设备登陆状态置为0时,读取数据库时出错,错误信息{0}", e.Message); logHelper.Error(error); } } finally { } }
public bool send(byte[] buffer, int offset, int length) { string info = ""; if (userToken.DeviceInfo != null) { info = string.Format("向DTU客户端(序号为:{0})发送数据,十六进制表示为:{1}", userToken.DeviceInfo.SerialString, FormatHelper.ByteArrayToHexString(buffer, offset, length)); } else { info = string.Format("向DTU客户端发送数据,十六进制表示为:{0}", FormatHelper.ByteArrayToHexString(buffer, offset, length)); } ShowLogData.add(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":[" + userToken.ConnectedSocket.RemoteEndPoint.ToString() + "]发送:" + info); LogHelper.Info(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":[" + userToken.ConnectedSocket.RemoteEndPoint.ToString() + "]发送:" + info); AsyncSendBufferManager sendBufferManager = userToken.AsyncSendBufferManager; sendBufferManager.startPacket(); sendBufferManager.DynamicBufferManager.writeBuffer(buffer, offset, length); sendBufferManager.endPacket(); bool result = true; if (!isSending) { int packetOffset = 0; int packetCount = 0; if (sendBufferManager.getFirstPacket(ref packetOffset, ref packetCount)) { isSending = true; //每一次发送时,更新时间 userToken.ActiveDateTime = DateTime.Now; result = server.sendAsyncEvent(userToken.ConnectedSocket, userToken.SendAysncEvetnArgs, sendBufferManager.DynamicBufferManager.Buffer, packetOffset, packetCount); } } return(result); }
public void closeClientSocket(AsyncSocketUserToken token, bool isUpdate) { if (token.DeviceList != null) { if (token.isClose) { if (SysCache.ShowInfoLog) { string info = string.Format(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":[" + token.ConnectedSocket.RemoteEndPoint.ToString() + "]:DTU通信服务,客户端{0}正在关闭", token.DeviceList.DeviceNo); ShowLogData.add(info); LogHelper.Info(info); } return; } token.isClose = true; if (SysCache.ShowInfoLog) { string info = string.Format(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":[" + token.ConnectedSocket.RemoteEndPoint.ToString() + "]:DTU通信服务,客户端{0},断开连接", token.DeviceList.DeviceNo); ShowLogData.add(info); LogHelper.Info(info); } if (isUpdate) { token.DeviceList.Online = 0; token.DeviceList.LastUpdate = DateTime.Now; token.DeviceList.TerminalState = "设备断开连接"; token.InvokeElement.proxySendDeviceList(token.DeviceList, null); /*未完成 更新终端状态*/ token.InvokeElement.updateDeviceList(token.DeviceList); } List <string> list = OnlineDeviceService.GetDeviceNoSubList(token.DeviceList.Id); if (list != null && list.Count > 0) { foreach (string str in list) { Device device = OnlineDeviceService.GetOnline(str); if (device != null) { if (SysCache.ShowInfoLog) { string info = string.Format(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":[" + token.ConnectedSocket.RemoteEndPoint.ToString() + "]:DTU通信服务,客户端{0},从站断开连接,主站{1}断开", device.DeviceNo, token.DeviceList.DeviceNo); ShowLogData.add(info); LogHelper.Info(info); } device.Online = 0; device.LastUpdate = DateTime.Now; device.TerminalState = "设备断开连接"; token.InvokeElement.proxySendDeviceList(device, null); token.InvokeElement.updateDeviceList(device); } } } string deviceNo = DeviceModule.GetFullDeviceNoByID(token.DeviceList.Id); OnlineDeviceService.RemoveOnline(deviceNo); } //修改于 2015-4-20 if (token.ConnectedSocket == null) { return; } try { token.ConnectedSocket.Shutdown(SocketShutdown.Both); } catch (SocketException) { } catch (NullReferenceException e) { if (SysCache.ShowErrorLog) { string error = string.Format("程序关闭连接时出错,错误信息{0}", e.Message); LogHelper.Error(error); } } /* * * if (showInfoLog) * { * string info = string.Format(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":[" + token.ConnectedSocket.RemoteEndPoint.ToString() + "]:DTU通信服务,释放信号量资源"); * ShowLogData.add(info); * LogHelper.Info(info); * } */ //start update by kqz 2017-2-3修改,由之前的注释修改成不注释 //由于在关闭掉客户端的时候,没有将此连接上来的客户端从已经连接的客户端集合中删除掉,所以导致一个客户端成功连接上后,再次断开 //下次连接,如果IP地址不同则连接不成功现象。 //并将此客户端资源回收到池中 //释放信号量资源 this.maxConnection.Release();//update by kqz 2017-3-28 9:34 将原来的注释取消 this.asyncSocketUserTokenPool.push(token); if (showInfoLog) { string info = string.Format(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":[" + token.ConnectedSocket.RemoteEndPoint.ToString() + "]:DTU通信服务,并将此客户端资源回收到池中,池中剩余数量{0}", asyncSocketUserTokenPool.Count); ShowLogData.add(info); LogHelper.Info(info); } //正在连接的集合中祛除此客户端信息 this.asyncSocketUserTokenList.remove(token); if (showInfoLog) { string info = string.Format(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":[" + token.ConnectedSocket.RemoteEndPoint.ToString() + "]:DTU通信服务,正在连接的集合中祛除此客户端信息,剩余连接数量{0}", asyncSocketUserTokenList.count()); ShowLogData.add(info); LogHelper.Info(info); } // end update by kqz 2017-2-3修改,由之前的注释修改成不注释 token.ConnectedSocket.Close(); token.ConnectedSocket = null; token.isClose = false; }
public void updateDevice(Device device) { if (SysCache.ShowInfoLog) { string info = string.Format(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":[" + device.Id + "]:准备修改token设备信息,id:{0}", device.Id); ShowLogData.add(info); LogHelper.Info(info); } bool isUpdate = false; try { if (AsyncSocketUserTokenList != null) { if (AsyncSocketUserTokenList.UserTokenList != null) { if (SysCache.ShowInfoLog) { string info4 = string.Format(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":[" + device.Id + "]:AsyncSocketUserTokenList.UserTokenList数量:{0}", AsyncSocketUserTokenList.UserTokenList.Count); ShowLogData.add(info4); LogHelper.Info(info4); } foreach (AsyncSocketUserToken token in AsyncSocketUserTokenList.UserTokenList) { if (token.DeviceList == null) { closeClientSocket(token, false); } if (token.DeviceList != null && token.DeviceList.Id == device.Id) { if (SysCache.ShowInfoLog) { string info1 = string.Format(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":[" + token.ConnectedSocket.RemoteEndPoint.ToString() + "]:DTU通信服务,设备信息修改,id:{0}", token.DeviceList.Id); ShowLogData.add(info1); LogHelper.Info(info1); } token.DeviceList = device; isUpdate = true; break; } } } else { if (SysCache.ShowInfoLog) { string info4 = string.Format(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":[" + device.Id + "]:无法修改token设备信息,id:{0},AsyncSocketUserTokenList.UserTokenList不存在", device.Id); ShowLogData.add(info4); LogHelper.Info(info4); } } } else { if (SysCache.ShowInfoLog) { string info3 = string.Format(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":[" + device.Id + "]:无法修改token设备信息,id:{0},AsyncSocketUserTokenList不存在", device.Id); ShowLogData.add(info3); LogHelper.Info(info3); } } } catch (Exception ex) { if (SysCache.ShowInfoLog) { string info3 = string.Format(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":[" + device.Id + "]:修改token设备信息出错,id:{0},错误:{1}", device.Id, ex.Message); ShowLogData.add(info3); LogHelper.Info(info3); } } if (SysCache.ShowInfoLog) { if (isUpdate) { string info2 = string.Format(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":[" + device.Id + "]:修改token设备信息成功,id:{0}", device.Id); ShowLogData.add(info2); LogHelper.Info(info2); } else { string info2 = string.Format(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":[" + device.Id + "]:修改token设备信息失败,id:{0}", device.Id); ShowLogData.add(info2); LogHelper.Info(info2); } } }
private void processAccepte(SocketAsyncEventArgs args) { //update by kqz 2017-3-27 try { //从池中取出一个空闲的异步操作对象 AsyncSocketUserToken token = this.asyncSocketUserTokenPool.pop(); //将此对象添加到正在连接集合中 this.asyncSocketUserTokenList.add(token); //设置保存连接socket token.ConnectedSocket = args.AcceptSocket; token.ConnectedTime = DateTime.Now; token.ActiveDateTime = DateTime.Now; try { //对连接后的socket对象投递接收请求 //投递异步操作对象AsyncSocketUserToken中的ReceiveAysncEventArgs //进行数据接收处理时,也是用这个ReceiveAysncEventArgs if (SysCache.ShowInfoLog) { if (token.ConnectedSocket.RemoteEndPoint != null) { LogHelper.Info(string.Format("DTU通信服务连接上一个客户端,信息为{0}", token.ConnectedSocket.RemoteEndPoint.ToString())); ShowLogData.add(string.Format("DTU通信服务连接上一个客户端,信息为{0}", token.ConnectedSocket.RemoteEndPoint.ToString())); } } //ShowLogData.add(string.Format("剩余线程池数量:{0}", this.asyncSocketUserTokenPool.Count)); #region add 2015-4-21 当连接上来后,回传一个"%" if (token.InvokeElement == null) { token.InvokeElement = new DTUInvokeElement(this, token); } //token.InvokeElement.SendData.addData(ProtocolKey.SendHeartThrob); //token.InvokeElement.send(); #endregion bool willRaiseEvent = token.ConnectedSocket.ReceiveAsync(token.ReceiveAysncEventArgs); if (!willRaiseEvent) { lock (token) { processReceive(token.ReceiveAysncEventArgs); } } } catch (Exception e) { if (SysCache.ShowErrorLog) { string error = ""; if (token.ConnectedSocket.RemoteEndPoint != null) { error = string.Format("DTU通信服务客户端{0}在投递接收请求时出错,错误信息为{1}", token.ConnectedSocket.RemoteEndPoint.ToString(), e.Message); } else { error = string.Format("在投递接收请求时出错,错误信息为{0}", e.Message); } LogHelper.Error(error); } closeClientSocket(token, true); } finally { //数据是否处理成功,都要进行下一次的异步接收 startAccept(args); } } catch (Exception ex) { LogHelper.Error("----------------异常信息为---------" + ex.Message + "===" + ex.InnerException.Message); } }
void DataSyn_OnLogHandler(string msg) { ShowLogData.add("【" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "】数据同步信息:" + msg); }
//根据信息的种类 ,进行处理:1.数据信息,发送给DTU 2.控制命令,发送给WEB 3.设备列表,更新显示表格 private void proxyProcess(DataTransfer transfer) { switch (transfer.TransferType) { case DataTransferType.DataTransferDataInfo: { DataTransferInfo info = transfer.TransferDataInfo; DeviceInfo di = new DeviceInfo(); di.Parse(info.DeviceNo); string DeviceFullNo = DeviceModule.DeviceNo_Hex2Normal(di.SerialString); string DeviceFullNoMain = DeviceModule.GetDeviceNoMain(DeviceFullNo); bridge.sendToDtu(DeviceFullNo, DeviceFullNoMain, info.Data, info.Offset, info.Length); break; } case DataTransferType.DataTransferCommand: { DTU.GateWay.Protocol.Command command = transfer.TransferCommand; bridge.sendToWeb(command.DeviceInfo.SerialLong, command); break; } case DataTransferType.DataTransferDeviceList: { Device deviceList = transfer.DeviceList; DeviceEvent deviceEvent = transfer.DeviceEvent; updateDeviceListInGridView(deviceList, deviceEvent); break; } case DataTransferType.DataTransferLog: { break; } case DataTransferType.DataTransferUpdateDevice: { string kt = transfer.KeyType; string key = transfer.Key; if (SysCache.ShowInfoLog) { ShowLogData.add("更新设备缓存:" + kt + "," + key); logHelper.Info("更新设备缓存:" + kt + "," + key); } if (kt == "01") { Device device = DeviceModule.GetDeviceByFullDeviceNo_DB(key); if (device != null) { DeviceModule.UpdateDeviceInfo(device); if (dtuServer != null) { dtuServer.updateDevice(device); } updateDeviceListInGridView(device, null); } else { if (SysCache.ShowInfoLog) { ShowLogData.add("更新设备缓存:" + kt + "," + key + " 无法更新设备不存在"); logHelper.Info("更新设备缓存:" + kt + "," + key + " 无法更新设备不存在"); } } } else if (kt == "02") { DeviceModule.RemoveDeviceInfo(key); lock (this.deviceListsDataGridView) { int rows = this.deviceListsDataGridView.Rows.Count; for (int i = 0; i < rows; i++) { object obj = this.deviceListsDataGridView.Rows[i].Cells[1].Value; if (obj != null) { string val = obj.ToString(); if (val.Equals(key)) { this.deviceListsDataGridView.Rows.Remove(this.deviceListsDataGridView.Rows[i]); return; } } } } } break; } case DataTransferType.DataTransferUpdateCardUser: { string kt = transfer.KeyType; string key = transfer.Key; ShowLogData.add("更新用户卡缓存:" + kt + "," + key); if (kt == "01") { CardUser cardUser = CardUserModule.GetCardUserBySerialNumber_DB(key); if (cardUser != null) { CardUserModule.UpdateCardUserInfo(cardUser); } } else if (kt == "02") { CardUserModule.RemoveCardUserInfo(key); } break; } case DataTransferType.DataTransferUpdateDistrict: { ShowLogData.add("更新地区缓存"); initDistrictTree(); break; } } }
public bool processPacket(byte[] buffer, int offset, int length) { int pos = 0; while (pos < length) { try { if (buffer[pos] == HexStringUtility.StrToByteArray(ProtocolKey.ReceiveHeartThrob)[0] || length - pos < 14) { if (userToken.DeviceInfo != null && userToken.DeviceList != null) { userToken.DeviceList.Online = 1; userToken.DeviceList.LastUpdate = DateTime.Now; userToken.DeviceList.Remark = FormatHelper.ByteArrayToHexString(buffer, offset + pos, length - pos); userToken.DeviceList.TerminalState = "心跳"; updateDeviceList(userToken.DeviceList); string FullDeviceNo = DeviceModule.GetFullDeviceNoByID(userToken.DeviceList.Id); OnlineDeviceService.AddOnline(FullDeviceNo, userToken.DeviceList); DeviceEvent deviceEvent = new DeviceEvent(); deviceEvent.DeviceNo = userToken.DeviceInfo.DeviceNo; deviceEvent.EventTime = userToken.DeviceList.LastUpdate; deviceEvent.EventType = userToken.DeviceList.TerminalState; deviceEvent.Remark = ""; deviceEvent.RawData = FormatHelper.ByteArrayToHexString(buffer, offset + pos, length - pos); proxySendDeviceList(userToken.DeviceList, deviceEvent); } byte[] data = HexStringUtility.StrToByteArray("%"); send(data, 0, data.Length); if (SysCache.ShowInfoLog) { string info1 = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":[" + userToken.ConnectedSocket.RemoteEndPoint.ToString() + "]响应(信息不对):" + "长度不到14"; LogHelper.Info(info1); ShowLogData.add(info1); } if (length - pos < 14) { break; } else { pos += 1; } } else if (buffer[pos] == BaseProtocol.BeginChar) { int bodyLength = buffer[pos + 1]; //长度 byte[] bs = new byte[5 + bodyLength]; Array.Copy(buffer, pos, bs, 0, bs.Length); processCommandBase(bs); pos += 5 + bodyLength; } else if (buffer[pos] == WaterBaseProtocol.BeginChar[0] && buffer[pos + 1] == WaterBaseProtocol.BeginChar[1]) { byte[] bs_UpOrDown_Length = new byte[2]; Array.Copy(buffer, pos + 11, bs_UpOrDown_Length, 0, 2); string str_UpOrDown_Length = HexStringUtility.ByteArrayToHexString(bs_UpOrDown_Length).ToUpper(); string str_Length = str_UpOrDown_Length.Substring(1, 3); int bodyLength = Convert.ToInt32(str_Length, 16); //正文长度 int baseLength = 0; //其它长度 baseLength += 2; //帧起始符 baseLength += 6; //中心站及遥测站 baseLength += 2; //密码 baseLength += 1; //功能码 baseLength += 2; //报文上下行表示及长度 baseLength += 1; //报文起始符 baseLength += 1; //报文结束符 baseLength += 2; //校验码 byte[] bs = new byte[baseLength + bodyLength]; Array.Copy(buffer, pos, bs, 0, bs.Length); processCommandWater(bs); pos += baseLength + bodyLength; } else { pos += 1; } } catch (Exception ex) { if (userToken.DeviceInfo != null && userToken.DeviceList != null) { userToken.DeviceList.Online = 1; userToken.DeviceList.LastUpdate = DateTime.Now; userToken.DeviceList.Remark = FormatHelper.ByteArrayToHexString(buffer, offset, length); userToken.DeviceList.TerminalState = "心跳"; updateDeviceList(userToken.DeviceList); string FullDeviceNo = DeviceModule.GetFullDeviceNoByID(userToken.DeviceList.Id); OnlineDeviceService.AddOnline(FullDeviceNo, userToken.DeviceList); DeviceEvent deviceEvent = new DeviceEvent(); deviceEvent.DeviceNo = userToken.DeviceInfo.DeviceNo; deviceEvent.EventTime = userToken.DeviceList.LastUpdate; deviceEvent.EventType = userToken.DeviceList.TerminalState; deviceEvent.Remark = ""; deviceEvent.RawData = FormatHelper.ByteArrayToHexString(buffer, offset + pos, length - pos); proxySendDeviceList(userToken.DeviceList, deviceEvent); } byte[] data = HexStringUtility.StrToByteArray("%"); send(data, 0, data.Length); if (SysCache.ShowInfoLog) { string info1 = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":[" + userToken.ConnectedSocket.RemoteEndPoint.ToString() + "]响应(信息不对):" + "【错误】【pos:" + pos + "】:" + ex.Message; LogHelper.Info(info1); ShowLogData.add(info1); } break; } } return(true); }