supersocket client 的简单使用方法

因为须要在服务端和客户端持续通讯,因而在网上找了很久的socket通讯工具。刚开始想直接用.net自带的socket通讯,后来担忧不够稳定健壮,毕竟本身不专业。找来找去以为supersocket还能够,可是说实话,他们的帮助文档写的真是太烂了,使用也不够简单易懂,折腾了一阵大体明白如何使用。服务器

1,在nuget上引用supersocket.clientengine和supersocket.protobasesocket

2,定义一个filter的类,protobase提供了5种预约义的方式,这里采用第二种,即定义数据头和尾的方式:async

  • TerminatorReceiveFilter
  • BeginEndMarkReceiveFilter
  • FixedHeaderReceiveFilter
  • FixedSizeReceiveFilter
  • CountSpliterReceiveFilter
class MyBeginEndMarkReceiveFilter : BeginEndMarkReceiveFilter<StringPackageInfo>
        {
            public MyBeginEndMarkReceiveFilter(string begin,string end)
            : base(Encoding.UTF8.GetBytes(begin), Encoding.UTF8.GetBytes(end))
            {
                this.begin = begin;
                this.end = end;
            }
            string begin;
            string end;
            public override StringPackageInfo ResolvePackage(IBufferStream bufferStream)
            {
                //获取接收到的完整数据,包括头和尾
                var body = bufferStream.ReadString((int)bufferStream.Length, Encoding.ASCII);
                //掐头去尾,只返回中间的数据
                body = body.Remove(body.Length - end.Length, end.Length);
                body = body.Remove(0, begin.Length);
                return new StringPackageInfo("", body, new string[] { });
            }
        }

3,封装一个简单的类。初始化类的时候设置好ip,端口,数据头和尾,而后设置要发送的数据属性data,而后调用startcomm方法开始每秒发送一次请求数据到服务器,订阅接收数据的事件newReceived。若是有须要能够随时更换data的内容,或者调用stopcomm中止发送数据  ide

class socketClient
    {
        SuperSocket.ClientEngine.EasyClient client;
        /// <summary>
        /// 定义服务端的ip地址和端口,以及接收数据的头和尾,只有在头和尾之间的数据才算有效数据
        /// </summary>
        /// <param name="ip">ip地址</param>
        /// <param name="port">服务端口</param>
        /// <param name="startFilter">数据头</param>
        /// <param name="endFilter">数据尾</param>
        public socketClient(string ip, int port, string startFilter, string endFilter)
        {
            this.ip = ip;
            this.port = port;
            if (!string.IsNullOrEmpty(startFilter)) this.startFilter = startFilter;
            if (!string.IsNullOrEmpty(endFilter)) this.endFilter = endFilter;
            client = new SuperSocket.ClientEngine.EasyClient();
            client.Initialize(new MyBeginEndMarkReceiveFilter(this.startFilter,this.endFilter), onReceived);
        }
        string ip;
        int port;
        string startFilter = "!!!";
        string endFilter = "###";
        bool cycleSend = false;
        /// <summary>
        /// 要发送到服务端的数据
        /// </summary>
        public string data { get; set; } = "hello,this is super client\r\n";
        public void startComm()
        {//开始循环发送数据
            cycleSend = true;
            System.Threading.Thread _thread = new System.Threading.Thread(sendData);
            _thread.IsBackground = true;
            _thread.Start();            
        }
        public void sendData()
        {//采用线程间隔一秒发送数据,防止界面卡死
            while (cycleSend)
            {
                if (!client.IsConnected)
                {
                    connectToServer(ip, port);
                }
                if (client.IsConnected)
                {
                    client.Send(Encoding.ASCII.GetBytes("hello,this is super client\r\n"));
                }
                System.Threading.Thread.Sleep(1000);
            }
        }
        public void stopComm()
        {//中止循环发送数据
            cycleSend = false;
        }
        public async void connectToServer(string ip, int port)
        {//链接到服务端
            var connected = await client.ConnectAsync(new IPEndPoint(IPAddress.Parse(ip), port));
            if (connected)
            {
                //发送链接信息
                client.Send(Encoding.ASCII.GetBytes("build connection"));
            }
        }
        public System.EventHandler newReceived;
        private void onReceived(StringPackageInfo stringPackageInfo)
        {//当读取到数据,触发一个事件,方便外部接收数据
            if (newReceived != null)
            {
                newReceived(stringPackageInfo.Body, new EventArgs());
            }
        }
    }
相关文章
相关标签/搜索