/// <summary> /// 连接服务 /// </summary> /// <param name="url"></param> /// <param name="data"></param> /// <returns></returns> public static string GetContentFromUrl(string url, string data) { Socket sokClient = null; string Message = ""; try { sokClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress address = IPAddress.Parse(url); IPEndPoint point = new IPEndPoint(address, 8000); sokClient.Blocking = true; sokClient.Connect(point); char[] cmgs = data.ToCharArray(); //字符串转字符数组 byte[] message = new byte[1024]; message = Encoding.Default.GetBytes(data); sokClient.Send(message); byte[] totalBytes = null; int receiveLength = 0; do { byte[] buffer = new byte[1024]; receiveLength = sokClient.Receive(buffer, buffer.Length, 0); if (totalBytes == null) { totalBytes = new byte[receiveLength]; Buffer.BlockCopy(buffer, 0, totalBytes, 0, receiveLength); } else { byte[] appendBytes = new byte[receiveLength]; Buffer.BlockCopy(buffer, 0, appendBytes, 0, receiveLength); byte[] newTotalBytes = new byte[receiveLength + totalBytes.Length]; Buffer.BlockCopy(totalBytes, 0, newTotalBytes, 0, totalBytes.Length); Buffer.BlockCopy(appendBytes, 0, newTotalBytes, totalBytes.Length, appendBytes.Length); totalBytes = newTotalBytes; } //Message = Message + Encoding.Default.GetString(buffer, 0, bytes); if (sokClient.Available <= 0) { break; } } while (receiveLength > 0 && receiveLength == 1024); Message = Encoding.Default.GetString(totalBytes); return Message; } catch (Exception ex) { return ex.Message; } finally { sokClient.Close(); }
while条件不满足,那就只执行一次了。
调试时是正常的
@锈戒: 你用Consle或其他方式,打印while里面的结果看看。
调试时你看得到正常执行,不调试你能看得到不正常执行?你怎么知道只执行一次???
因为数据少了呗
@锈戒: Message = Encoding.Default.GetString(totalBytes);
return Message;
你的返回都不是一个叠加的过程,怎么可能给你返回多数据,执行多少次都只会给你返回最后一条吧
@阿 牛: totalbytes 已经是叠加完成的数据了 ~~好了
判断问题 if (sokClient.Available <= 0) { break; }
删除 if (sokClient.Available <= 0) { break; }