using System;
using System.Text;
namespace Curtain.Net.Sockets.PLC.Model
{
///
/// 基本Socket服务模型
///
public class SimpleSocketServerModel : ServerModel
{
///
/// 响应报文-头长度
///
public override int HeadLength
{
get
{
return (FormatType == CommandFormatType.PLCCommand ? 4 : 1);
}
}
///
/// 根据响应报文-头,计算响应报文-文本长度
///
/// 报文
/// 响应报文-文本长度
public override int GetContentLength(ReceiveSession rs)
{
try
{
return Convert.ToInt32(Encoding.ASCII.GetString(rs.HeadBytes, 2, 2), 16);
}
catch
{
return -1;
}
}
///
/// 验证响应报文-头
///
/// 报文
/// 是否通过
public override bool CheckHead(ReceiveSession rs)
{
if (rs == null || rs.HeadBytes == null || rs.HeadBytes.Length != HeadLength)
{
return false;
}
if (FormatType == CommandFormatType.StartStopChar)
{
return CheckHeadChar(rs.HeadBytes);
}
rs.Command = ToCommandFromReceive(rs.HeadBytes);
rs.Head = ToHeadFromReceive(rs.HeadBytes);
return true;
}
///
/// 接收字节转换为命令
///
/// 接收字节
/// 响应报文
public override string ToCommandFromReceive(byte[] receive)
{
if (receive == null || receive.Length == 0)
{
return null;
}
return Encoding.ASCII.GetString(receive, 0, 2);
}
///
/// 接收字节转换为报文头
///
/// 接收字节
/// 响应报文
public override string ToHeadFromReceive(byte[] receive)
{
if (receive == null || receive.Length == 0)
{
return null;
}
//return Encoding.ASCII.GetString(receive, 0, HeadLength);
return Encoding.ASCII.GetString(receive);
}
///
/// 接收字节转换为报文正文
///
/// 接收字节
/// 响应报文
public override string ToContentFromReceive(byte[] receive)
{
if (receive == null || receive.Length == 0)
{
return null;
}
return Encoding.ASCII.GetString(receive);
}
///
/// 命令报文转换为发送字节
///
/// 命令报文
/// 发送字节
public override byte[] ToSendFromCommand(string command)
{
if (string.IsNullOrEmpty(command))
{
return null;
}
return Encoding.ASCII.GetBytes(command);
}
}
}