using Hanhe.iWCS.Common; using SuperSocket.SocketBase; using SuperSocket.SocketBase.Protocol; using System; using System.Linq; using System.Text; namespace Hanhe.iWCS.JingmenGEMTwoTCP { public class WCSSession : AppSession { /// /// 设备编号 /// public string deviceCode { get; set; } protected override void OnSessionStarted() { SessionInstance.Instance.AddSession(this.AppServer.GetSessionByID(this.SessionID)); string msg = DateTime.Now.ToString() + "-a new Session connectioned,new Client Ip=" + this.RemoteEndPoint.Address + " and Port=" + this.RemoteEndPoint.Port + ""; Console.WriteLine(msg); } /// /// PLC信号指令 /// /// protected override void HandleUnknownRequest(BinaryRequestInfo requestInfo) { var hex = BitConverter.ToString(requestInfo.Body, 0).Replace("-", string.Empty).ToLower(); WCSSession currSession = this.AppServer.GetSessionByID(this.SessionID); var ip = currSession.RemoteEndPoint.Address.ToString(); var port = currSession.RemoteEndPoint.Port; //Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + "--receive:" + hex + "--length:" + hex.Length); SessionInstance.Instance._IProtocolAnalysis.StringRequestInfo(hex, ip, port, currSession.SessionID); SessionInstance.Instance._IProtocolAnalysis.StringRequestInfo(hexToStr(hex), ip, port); var res = requestInfo.Body.ToList();res.Add(36);res.Add(36); SessionInstance.Instance.PLCSend(ip, port, res.ToArray()); } private static string hexToStr(string hexString) { hexString = hexString.Replace(" ", ""); if ((hexString.Length % 2) != 0) hexString += " "; byte[] returnBytes = new byte[hexString.Length / 2]; for (int i = 0; i < returnBytes.Length; i++) returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16); return Encoding.ASCII.GetString(returnBytes); } protected override void HandleException(Exception e) { this.Send("Application error: {0}", e.Message); } protected override void OnSessionClosed(CloseReason reason) { //add you logics which will be executed after the session is closed SessionInstance.Instance.SessionRemove(this.SessionID); base.OnSessionClosed(reason); string msg = DateTime.Now.ToString() + "-a connection Client Ip=" + this.RemoteEndPoint.Address + " and Port=" + this.RemoteEndPoint.Port + " is SocketClosed"; Console.WriteLine(msg); CMMLog.Debug(msg); //ProtocolAnalysis.Instance._Logger.DeleteOnline(this.RemoteEndPoint.Address.ToString(), this.RemoteEndPoint.Port); } } }