using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using SuperSocket.SocketBase.Protocol;
namespace SuperWebSocket.SubProtocol
{
///
/// Json SubCommand base
///
/// The type of the web socket session.
/// The type of the json command info.
public abstract class JsonSubCommandBase : SubCommandBase
where TWebSocketSession : WebSocketSession, new()
{
private const string m_QueryTemplateA = "{0}-{1} {2}";
private const string m_QueryTemplateB = "{0} {1}";
private bool m_IsSimpleType = false;
private Type m_CommandInfoType;
///
/// Initializes a new instance of the class.
///
public JsonSubCommandBase()
{
m_CommandInfoType = typeof(TJsonCommandInfo);
if (m_CommandInfoType.IsSimpleType())
m_IsSimpleType = true;
}
///
/// Executes the command.
///
/// The session.
/// The request info.
public override void ExecuteCommand(TWebSocketSession session, SubRequestInfo requestInfo)
{
if (string.IsNullOrEmpty(requestInfo.Body))
{
ExecuteJsonCommand(session, default(TJsonCommandInfo));
return;
}
TJsonCommandInfo jsonCommandInfo;
LocalDataStoreSlot tokenSlot = null;
if (!string.IsNullOrEmpty(requestInfo.Token))
tokenSlot = session.SetCurrentToken(requestInfo.Token);
try
{
if (!m_IsSimpleType)
jsonCommandInfo = (TJsonCommandInfo)session.AppServer.JsonDeserialize(requestInfo.Body, m_CommandInfoType);
else
jsonCommandInfo = (TJsonCommandInfo)Convert.ChangeType(requestInfo.Body, m_CommandInfoType);
ExecuteJsonCommand(session, jsonCommandInfo);
}
finally
{
if (tokenSlot != null)
Thread.SetData(tokenSlot, null);
}
}
///
/// Executes the json command.
///
/// The session.
/// The command info.
protected abstract void ExecuteJsonCommand(TWebSocketSession session, TJsonCommandInfo commandInfo);
///
/// Gets the json message.
///
/// The session.
/// The name.
/// The token.
/// The content.
///
protected string GetJsonMessage(TWebSocketSession session, string name, string token, object content)
{
string strOutput;
//Needn't serialize primitive type object
if (content.GetType().IsSimpleType())
strOutput = content.ToString();
else
strOutput = session.AppServer.JsonSerialize(content);
if (string.IsNullOrEmpty(token))
return string.Format(m_QueryTemplateB, name, strOutput);
else
return string.Format(m_QueryTemplateA, name, token, strOutput);
}
}
}