using log4net; using SuperSocket.SocketBase; using SuperSocket.SocketBase.Protocol; using SuperSocket.WebSocket; using System; using System.Collections.Generic; using System.Linq; using System.Text; using SuperSocket.WebSocket.Protocol; namespace POSV.WindowsService { /// /// 自定义连接类 /// public class WebSocketSessionEx : JsonWebSocketSession { private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger(); /// /// 客户端名称 /// public string Name { get; set; } public new WebSocketServerEx AppServer { get { return (WebSocketServerEx)base.AppServer; } } /// /// 新连接 /// protected override void OnSessionStarted() { base.OnSessionStarted(); var name = this.Path; if (!string.IsNullOrEmpty(name)) { name = name.Substring(1); } this.Name = name; var result = SessionManager.AddSession(name, this); if (result.Item1) { logger.Info("["+ name + "]新用户连接到服务器了"); this.Send("\n\rHello User"); } else { logger.Error("[" + name + "]"+result.Item2); this.Close(CloseReason.ServerClosing); } } /// /// 未知的Command /// /// protected override void HandleUnknownRequest(IWebSocketFragment requestInfo) { base.HandleUnknownRequest(requestInfo); this.Send("\n\r未知的命令"); } /// /// 捕捉异常并输出 /// /// protected override void HandleException(Exception e) { logger.Error(e,"HandleException"); this.Send("\n\r异常: {0}", e.Message); } /// /// 连接关闭 /// /// protected override void OnSessionClosed(CloseReason reason) { base.OnSessionClosed(reason); var name = this.Path; if (!string.IsNullOrEmpty(name)) { name = name.Substring(1); } this.Name = null; SessionManager.RemoveSession(name); logger.Info("["+ name + "]客户端断开了连接"); } } }