socket服务器发送大数据,客户端循环接收

服务器端代码:

 public void SendTextMsg(string str)
        {
            int maxlength = 1000;
            int page = 0;
            if (str.Length % maxlength == 0)
            {
                page = str.Length / maxlength;
            }
            else
            {
                page = str.Length / maxlength + 1;
            }
            for (int i = 0; i < page; i++)
            {
                string tmp = null;
                if (i < page - 1)
                {
                    tmp = str.Substring(i * maxlength, maxlength);
                }
                else
                {
                    tmp = str.Substring(i * maxlength);
                }
                var jobj = new
                {
                    total = page,
                    index = i,
                    data = tmp
                };
                string jstr = Newtonsoft.Json.JsonConvert.SerializeObject(jobj);
                string bstr = Common.ToBase64(jstr);//编码转换,起到加密和防止汉字乱码的作用
                //System.Diagnostics.Debug.WriteLine("{0} {1}", jstr.Length, jstr);
                base.Send(bstr+"#end#");
            }
        }

客户端代码:

try
            {
                chksocket();
                string jstr = getpara(msg, cmd);
                string mm = string.Format("LOGA {0}\r\n", jstr);
                byte[] buffer = Encoding.UTF8.GetBytes(mm);
                _socket.Send(buffer);
                Dictionary<int, string> data = new Dictionary<int, string>();
                string tmpData = "";
                while (true)
                {
                    buffer = new byte[1];
                    int rev = _socket.Receive(buffer);
                    string result = Encoding.UTF8.GetString(buffer);
                    tmpData += result;
                    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());
                        data.Add(index, ds);
                        tmpData = "";
                        if (data.Count == total)
                        {
                            break;
                        }
                    }
                }
                Dictionary<int, string> dic = data.OrderBy(p => p.Key).ToDictionary(p => p.Key, o => o.Value);
                StringBuilder sb = new StringBuilder();
                foreach (KeyValuePair<int, string> item in dic)
                {
                    sb.Append(item.Value);
                }
                return sb.ToString();
            }
            catch (Exception e)
            {
                throw e;
            }

你可能感兴趣的:(C#)