supersocket 客户端异步接收,可以实时接收服务器数据

 public delegate void DelegateMsg(object msg);
    public class SocketClient
    {
        Socket _client;
        IPEndPoint _ip;
        string _cmd;
        public DelegateMsg OnReceive;

        public SocketClient(string ip, int port, string command = null)
        {
            _client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _ip = new IPEndPoint(IPAddress.Parse(ip), port);
            _cmd = command == null ? "XFWA" : command;
        }

        public void Connect()
        {
            try
            {
                _client.Connect(_ip);
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        public void Send(string cmd, object data)
        {
            try
            {
                send(cmd, data);
            }
            catch (Exception e)
            {
                throw e;
            }

        }

        private void send(string cmd, object data)
        {
            var sobj = new { cmd = cmd, weburl = UConfig.WebUrl, data = data };
            string jobj = JsonConvert.SerializeObject(sobj);
            string msg = string.Format("{0} {1}\r\n", _cmd, jobj);
            byte[] bb = Encoding.UTF8.GetBytes(msg);
            if (_client.Connected == false)
            {
                throw new Exception("未连接到转发服务器");
            }
            _client.Send(bb);//发送
        }

        public void Recive()
        {
            byte[] data = new byte[10240];
            string msg;
            try
            {
                _client.BeginReceive(data, 0, data.Length, SocketFlags.None,
                asyncResult =>
                {
                    try
                    {
                        int length = _client.EndReceive(asyncResult);
                        OnReceive(Encoding.UTF8.GetString(data));
                        Recive();
                    }
                    catch (SocketException e)
                    {
                        msg = string.Format("转发服务器已离线:{0}", e.Message);
                        Console.WriteLine(msg);
                        Log.Err(msg);
                    }
                }, null);
            }
            catch (Exception ex)
            {
                Recive();
                msg = string.Format("接收出现错误:{0}", ex.Message);
                Console.WriteLine(msg);
                Log.Err(msg);
            }
        }


        public bool Connected
        {
            get
            {
                return _client.Connected;
            }
        }

        public void Close()
        {
            if (_client != null && _client.Connected)
            {
                _client.Close();
                _client = null;
            }
        }

调用:

public class Client
    {
        public static SocketClient Current;

    }
 Client.Current = new SocketClient(ip, port, "TRAN");
                Client.Current.OnReceive += new DelegateMsg(receive);
                Client.Current.Connect();
                Client.Current.Recive();
  static StringBuilder receiveMsg = new StringBuilder();
        static Dictionary<int, string> receiveData = new Dictionary<int, string>();
        static void receive(object msg)
        {
            #region 接收与转换数据
            msg = msg.ToString().TrimEnd('\0');
            string[] striparr = msg.ToString().Split(new string[] { "\r\n" }, StringSplitOptions.None);
            striparr = striparr.Where(s => !string.IsNullOrEmpty(s)).ToArray();

            foreach (var tmpData in striparr)
            {
                //if (tmpData.EndsWith("#end#"))
                //{
                string jstr = Common.FromBase64(tmpData.Replace("#end#", ""));
                JObject jobj = JObject.Parse(jstr);
                int index = int.Parse(jobj["index"].ToString());
                string ds = jobj["data"].ToString();
                int total = int.Parse(jobj["total"].ToString());
                receiveData.Add(index, ds);
                if (receiveData.Count == total)
                {
                    receiveMsg.Clear();
                    //合包
                    Dictionary<int, string> dic = receiveData.OrderBy(p => p.Key).ToDictionary(p => p.Key, o => o.Value);
                    foreach (KeyValuePair<int, string> item in dic)
                    {
                        receiveMsg.Append(item.Value);
                    }
                    receiveData.Clear();
                }
                //}
            }
            #endregion

            #region 处理数据

            try
            {
                JObject obj = JObject.Parse(receiveMsg.ToString());
                JsonResultObject robj = new JsonResultObject();
                robj.state = (EnumState)int.Parse(obj["state"].ToString());
                robj.msg = obj["msg"].ToString();
                robj.data = obj["data"];

                //ok时是心跳测试
                if (robj.data.ToString() != "ok")
                {
                    JObject jobj = JObject.Parse(robj.data.ToString());
                    if (jobj.ContainsKey("cmd"))
                    {
                        string cmd = jobj["cmd"].ToString();
                        switch (cmd)
                        {
                            case "newfile":
                                //
                                break;
                            default:
                                break;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                string showmsg = string.Format("转换为Json对象时出现错误,\r\n数据:{0}\r\n错误:{1}", receiveMsg.ToString(), e.Message);
                Console.WriteLine(showmsg);
                Log.Err(showmsg);
            }

            #endregion
        }

猜你喜欢

转载自blog.csdn.net/wyljz/article/details/80563019