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