由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。
源错误:
行 188: byte[] buffer = new byte[256];
行 189:
行 190: iNumber = socket.Receive(buffer, buffer.Length, SocketFlags.None);
行 191:
行 192: if (buffer.Length > iNumber)
|
源代码:
byte[] GetSocketBytes(Uri uri, byte[] headersData) { int iTotalCount = 0; List<byte[]> responseBytes = new List<byte[]>(10); using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { //socket.ReceiveTimeout = 10 * 1000; //socket.SendTimeout = 3 * 1000; socket.Connect(uri.Host, uri.Port); /* int connectTimes = 0; lable: connectTimes++; if (socket.Connected) { */ socket.Send(headersData); byte[] bufferFirst = new byte[256]; int iNumber = 0; iNumber = socket.Receive(bufferFirst, bufferFirst.Length, SocketFlags.None); iTotalCount = iNumber; if (bufferFirst.Length > iNumber) { byte[] temBuffer = new byte[iNumber]; Array.Copy(bufferFirst, 0, temBuffer, 0, iNumber); responseBytes.Add(temBuffer); } else { responseBytes.Add(bufferFirst); } while (iNumber > 0) { byte[] buffer = new byte[256]; iNumber = socket.Receive(buffer, buffer.Length, SocketFlags.None); if (buffer.Length > iNumber) { byte[] temBuffer = new byte[iNumber]; Array.Copy(buffer, 0, temBuffer, 0, iNumber); responseBytes.Add(temBuffer); } else { responseBytes.Add(buffer); } iTotalCount += iNumber; //索引位置增加 } /* } else { if (connectTimes <= 3) { System.Threading.Thread.Sleep(10); goto lable; } } */ socket.Close(); socket.Dispose(); } byte[] receiveData = new byte[iTotalCount]; int fillCount = 0; for (int i = 0; i < responseBytes.Count; i++) { byte[] data = responseBytes[i]; Array.Copy(data, 0, receiveData, fillCount, data.Length); fillCount += data.Length; } return receiveData; }
如果实在不行 你可以试一下 webclient这个类 它有load方法 可以下载html
抓包分析下,你的 headersData 可能不是格式正确的 HTTP HEADER 内容。
LS应该是正解,如果你浏览器能打开,socket打不开,那只能说你用socket法的请求报文是错误的