supersocket client接收字节数据

1.由于通过TCP接收字节数组。之前写的只能接收字符串。所以进行修改 


using StraightLineSorting.Equipment;
using StraightLineSorting.Helper;
using StraightLineSorting.MyTask;
using SuperSocket.Client;
using SuperSocket.ProtoBase;
using System.Diagnostics;
using System.Net;
using System.Text;

namespace StraightLineSorting.Communication
{
    public class TcpSupersocket
    {
        public static object o = new object();
        public static TcpSupersocket? Instance;         

        public static IEasyClient<IMPackage> mClient = new EasyClient<IMPackage>(new IMPipelineFilter()).AsClient(); 
 

        public static TcpSupersocket GetInstance()
        {
            if (Instance == null)
            {
                Instance = new TcpSupersocket();
            }
            return Instance;
        }

        public async void Connect()
        {
            await Task.Run(() =>
            {
               // ConnectServer();
                RunClientTest();
            });
        }
 

        private async void RunClientTest()
        {
            string msg; 
            string TCPTestIP = AppSettingsHelper.Configuration["PLC:IP"];
            int TCPTestPort = int.Parse(AppSettingsHelper.Configuration["PLC:Port"]);
 


            while (!await mClient.ConnectAsync(new IPEndPoint(IPAddress.Parse(TCPTestIP), TCPTestPort)))
            {
                msg = $" 连接失败!目标地址!{TCPTestIP} : {TCPTestPort} 等待30秒重试!";

                Debug.WriteLine(msg);

                LogHelper.Warn(msg);

                await Task.Delay(30 * 1000);
            };

            msg = $" 连接成功!目标地址!{TCPTestIP} : {TCPTestPort} ";
            LogHelper.Debug(msg);

            while (true)
            {
                var pp = await mClient.ReceiveAsync();
                if (pp != null)
                {
                    try
                    {
                        string ss = BitConverter.ToString(pp.Key);//  System.Text.Encoding.UTF8.GetString(pp.Key);
                        msg = $"【TCPClient】 【接收到数据】 {ss}";
                        LogHelper.Debug(msg); 
                       
                    }
                    catch (Exception ex)
                    {
                        msg = $"【TCPClient】 接收到数据异常 {ex.Message}";
                        LogHelper.Error(msg);
                    }
                }
                else
                {
                    // await Client.ConnectAsync(new IPEndPoint(IPAddress.Parse(TCPTestIP), TCPTestPort));
                }
            }
        }

 

        public void Send(string cmd)
        {
            try
            {
                byte[] byteArray = System.Text.Encoding.ASCII.GetBytes(cmd);
                mClient.SendAsync(byteArray);

                LogHelper.Info($"【TCPClient】 发送数据  [{cmd}]");
            }
            catch (Exception ex)
            {
                LogHelper.Error($"【TCPClient】 发送数据异常  {cmd} {ex.Message}");
            }
        }

        public void SendBytes(byte[] data)
        {
            try
            {
                lock (o)
                {
                    mClient.SendAsync(data);

                    LogHelper.Debug($" 【TCPClient】 发送数据 {BitConverter.ToString(data)}"); 
                }
            }
            catch (Exception ex)
            {
                // LogHelper.Error($"SuperSocket发送数据异常  {cmd} {ex.Message}");
            }
        }

        public void Dispose()
        {
            mClient.CloseAsync();
        }
    }
}

2.IMPackage

namespace StraightLineSorting.Equipment
{
 
    public class IMPackage
    {
        public IMPackage()
        {

        }

        public byte[] Key { get; set; } 
    }
}

3.IMpipelineFilter 我这里接收固定的32位字节数组

using SuperSocket.ProtoBase;
using System.Buffers;

namespace StraightLineSorting.Equipment
{
    /// <summary>
    /// 消息处理管道
    /// </summary>
    public class IMPipelineFilter : FixedHeaderPipelineFilter<IMPackage>
    {
        public IMPipelineFilter() : base(32)//key + id + id + bodyLength = 1+8+8+4
        {
        }

        /// <summary>
        /// 实现获取包体长度的方法
        /// </summary>
        /// <param name="buffer"></param>
        /// <returns></returns>
        protected override int GetBodyLengthFromHeader(ref ReadOnlySequence<byte> buffer)
        {
            var reader = new SequenceReader<byte>(buffer);

            return 0;// buffer.Length;
        }

        protected override IMPackage DecodePackage(ref ReadOnlySequence<byte> buffer)
        {
            IMPackage data = new IMPackage();
            var reader = new SequenceReader<byte>(buffer);

            data.Key = reader.Sequence.ToArray();// System.Text.Encoding.UTF8.GetBytes(reader.ReadString());// reader.ReadString().to;
            return data;
        }

    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值