You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

101 lines
2.7 KiB
C#

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
{
/// <summary>
/// 自定义连接类
/// </summary>
public class WebSocketSessionEx : JsonWebSocketSession<WebSocketSessionEx>
{
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
/// <summary>
/// 客户端名称
/// </summary>
public string Name { get; set; }
public new WebSocketServerEx AppServer
{
get { return (WebSocketServerEx)base.AppServer; }
}
/// <summary>
/// 新连接
/// </summary>
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);
}
}
/// <summary>
/// 未知的Command
/// </summary>
/// <param name="requestInfo"></param>
protected override void HandleUnknownRequest(IWebSocketFragment requestInfo)
{
base.HandleUnknownRequest(requestInfo);
this.Send("\n\r未知的命令");
}
/// <summary>
/// 捕捉异常并输出
/// </summary>
/// <param name="e"></param>
protected override void HandleException(Exception e)
{
logger.Error(e,"HandleException");
this.Send("\n\r异常: {0}", e.Message);
}
/// <summary>
/// 连接关闭
/// </summary>
/// <param name="reason"></param>
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 + "]客户端断开了连接");
}
}
}