|
|
|
|
using AsyncSocket;
|
|
|
|
|
using SLH.SSDMS.Common;
|
|
|
|
|
using SLH.SSDMS.Services;
|
|
|
|
|
using SLH.SSDMS.Services.serviceImpl;
|
|
|
|
|
using System;
|
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
using System.Linq;
|
|
|
|
|
using System.Text;
|
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
|
|
|
|
|
namespace SLH.SSDMS.Collect
|
|
|
|
|
{
|
|
|
|
|
public class AsyncSocket
|
|
|
|
|
{
|
|
|
|
|
private static AsyncSocketServer server = new AsyncSocketServer();
|
|
|
|
|
|
|
|
|
|
private static IBufferParse bufferParse = new BufferParse();
|
|
|
|
|
|
|
|
|
|
public static void init()
|
|
|
|
|
{
|
|
|
|
|
server.Completed += new Action<string, EnSocketAction>((key, enAction) =>
|
|
|
|
|
{
|
|
|
|
|
switch (enAction)
|
|
|
|
|
{
|
|
|
|
|
case EnSocketAction.Connect:
|
|
|
|
|
LogHelper.Info(String.Format("接收到来自{0}的连接", key));
|
|
|
|
|
break;
|
|
|
|
|
case EnSocketAction.SendMsg:
|
|
|
|
|
LogHelper.Info(String.Format("向客户端{0}发送了一条消息", key));
|
|
|
|
|
break;
|
|
|
|
|
case EnSocketAction.Close:
|
|
|
|
|
LogHelper.Info(String.Format("{0}关闭了连接", key));
|
|
|
|
|
break;
|
|
|
|
|
default:
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
server.Received += new Action<string, byte[]>((key, msg) =>
|
|
|
|
|
{
|
|
|
|
|
string bufferStr = StringChange.bytesToHexStr(msg, msg.Length);
|
|
|
|
|
LogHelper.Info(String.Format("收到客户端:{0}的数据:{1}", key, StringChange.bytesToHexStr(msg, msg.Length)));
|
|
|
|
|
|
|
|
|
|
if(bufferStr.Contains("A55A") && bufferStr.Contains("0D0A"))
|
|
|
|
|
{
|
|
|
|
|
byte[] bufferLength = msg.Skip(2).Take(2).ToArray();
|
|
|
|
|
int dataLen = Convert.ToInt32(StringChange.bytesToHexStr(bufferLength, bufferLength.Length), 16) + 1;
|
|
|
|
|
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
byte[] calByte = new byte[dataLen];
|
|
|
|
|
Array.Copy(msg, 2, calByte, 0, dataLen);
|
|
|
|
|
|
|
|
|
|
var info = checkUtil.BCC(calByte);
|
|
|
|
|
|
|
|
|
|
var test = msg[msg.Length - 2];
|
|
|
|
|
|
|
|
|
|
//判断校验
|
|
|
|
|
if (msg[msg.Length - 3] == info)
|
|
|
|
|
{
|
|
|
|
|
if (calByte[2] == 132)
|
|
|
|
|
{
|
|
|
|
|
sendMessage(bufferParse.ReadAnalysis(calByte).Result);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (calByte[2] == 98)
|
|
|
|
|
{
|
|
|
|
|
sendMessage(bufferParse.HeartAnalysis(calByte).Result);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (calByte[2] == 164)
|
|
|
|
|
{
|
|
|
|
|
//终端IO返回
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
|
|
|
|
LogHelper.Error("接收数据异常", ex);
|
|
|
|
|
throw;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
|
|
|
|
|
LogHelper.Info("异常指令:" + StringChange.bytesToHexStr(msg, msg.Length));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
server.StartAsync(7788);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private static void sendMessage(byte[] buffer)
|
|
|
|
|
{
|
|
|
|
|
server.SendAsync(buffer);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|