public AddRange ( IEnumerable, items ) : void | ||
items | IEnumerable, | |
Результат | void |
/* * 检索功能: * 给出一个物体对象,该函数负责将该物体可能发生碰撞的所有物体选取出来。该函数先查找物体所属的象限,该象限下的物体都是有可能发生碰撞的,然后再递归地查找子象限.. */ public FastList <CollisionComponent> Retrieve(CollisionComponent coll) { listCache.Clear(); //Debug.Log("m_childListCount " + m_childListCount); if (m_childListCount != 0) { bool[] indexList = GetRetrieveIndex(coll.area); for (int i = 0; i < 4; i++) { if (indexList[i]) { listCache.AddRange(m_childList[i].Retrieve(coll)); } } } listCache.AddRange(m_objectList); //Debug.Log("Retrieve " + listCache.Count + " depth " + m_depth); return(listCache); }
public static void Simulate() { if (GameStarted == false) { } else { bufferBytes.FastClear(); bufferBytes.AddRange(BitConverter.GetBytes(InfluenceFrameCount)); bufferBytes.AddRange(receivedBytes); receivedBytes.FastClear(); ClientManager.NetworkHelper.SendMessageToAll(MessageType.Frame, bufferBytes.ToArray()); InfluenceFrameCount++; } }
static IEnumerator receive(byte[] data) { yield return(LSUtility.WaitRealTime(UnityEngine.Random.Range(Latency, Latency + Jitter))); receivedBytes.AddRange(data); yield break; }
static IEnumerator Tick() { while (true) { if (IsSimulating && LockstepManager.GameStarted) { bufferBytes.FastClear(); bufferBytes.AddRange(BitConverter.GetBytes(InfluenceFrameCount)); InfluenceFrameCount++; bufferBytes.AddRange(receivedBytes); receivedBytes.FastClear(); Send(bufferBytes.ToArray()); } yield return(LSUtility.WaitRealTime(LockstepManager.DeltaTimeF * LockstepManager.InfluenceResolution)); } }
public byte[] GetBytes() { this.Serialize(); bufferBites.FastClear(); //Serialize header int headerLength = Header.Length; int headerArraySize = (headerLength - 1) / 8 + 1; bufferBites.Add((byte)headerArraySize); byte[] headerBytes = new byte[headerArraySize]; Header.CopyTo(headerBytes, 0); bufferBites.AddRange(headerBytes); //Serializing the good stuff for (int i = 0; i < Header.Length; i++) { if (Header.Get(i)) { bufferBites.Add(Data[i]); } } return(bufferBites.ToArray()); }
public unsafe ParameterCollection(ParameterCollection parameterCollection) { // Copy layout if (parameterCollection.layout != null) { layout = parameterCollection.layout; } // Copy parameter keys parameterKeyInfos.AddRange(parameterCollection.parameterKeyInfos); // Copy objects if (parameterCollection.ObjectValues != null) { ObjectValues = new object[parameterCollection.ObjectValues.Length]; for (int i = 0; i < ObjectValues.Length; ++i) { ObjectValues[i] = parameterCollection.ObjectValues[i]; } } // Copy data if (parameterCollection.DataValues != null) { DataValues = new byte[parameterCollection.DataValues.Length]; fixed(byte *dataValuesSources = parameterCollection.DataValues) fixed(byte *dataValuesDest = DataValues) { Utilities.CopyMemory((IntPtr)dataValuesDest, (IntPtr)dataValuesSources, DataValues.Length); } } }
internal void Duplicate(int start, int finish) { var sh = Offset - start; ops.AddRange(ops, start, finish); opData.AddRange(opData, start, finish); var nf = new FastList <Int32>(); foreach (var i in fixups) { if (i >= start && i <= finish) { var l = labels[opData[i]]; var nl = DefineLabel(); opData[sh + i] = nl.GetIndex(); labels[nl.GetIndex()] = l + sh; nf.Add(sh + i); } } fixups.AddRange(nf); }
//static FastList<Command> asdf = new FastList<Command>(); public static void SendCommand(Command com) { if (com == null) { return; } bufferedBytes.AddRange(com.Serialized); }
internal CodeAssembly() { modules = new FastList <CodeFrame>(); foreignModules = new FastList <ForeignModule>(); moduleMap = new Dictionary <String, Int32>(); quals = new FastList <Boolean>(); Instances = new Dictionary <Int64, Byte>(); Constructors = new FastList <ConstructorData>(); Types = new FastList <TypeData> { new TypeData(ElaTypeCode.None), new TypeData(ElaTypeCode.Integer), new TypeData(ElaTypeCode.Long), new TypeData(ElaTypeCode.Single), new TypeData(ElaTypeCode.Double), new TypeData(ElaTypeCode.Boolean), new TypeData(ElaTypeCode.Char), new TypeData(ElaTypeCode.String), new TypeData(ElaTypeCode.Unit), new TypeData(ElaTypeCode.List), new TypeData(ElaTypeCode.__Reserved), new TypeData(ElaTypeCode.Tuple), new TypeData(ElaTypeCode.Record), new TypeData(ElaTypeCode.Function), new TypeData(ElaTypeCode.Object), new TypeData(ElaTypeCode.Module), new TypeData(ElaTypeCode.Lazy), new TypeData(ElaTypeCode.__Reserved2), new TypeData(ElaTypeCode.__Reserved3) }; Cls = new FastList <Class>(); Cls.AddRange( new Class[] { new Class(), //ERR new IntegerInstance(), //INT new LongInstance(), //LNG new SingleInstance(), //SNG new DoubleInstance(), //DBL new BooleanInstance(), //BYT new CharInstance(), //CHR new StringInstance(), //STR new UnitInstance(), //UNI new ListInstance(), //LST new Class(), //TAB new TupleInstance(), //TUP new RecordInstance(), //REC new FunctionInstance(), //FUN new Class(), //OBJ new ModuleInstance(), //MOD new Class(), //LAZ new Class(), //RES2 new Class(), //RES3 }); }
internal IEnumerable <TraceVar> ObtainTraceVars(WorkerThread thread, Ela.Runtime.CallStack stack) { var sym = thread.Module.Symbols; var mem = stack.Peek(); var locals = mem.Locals; var captures = mem.Captures; var off = thread.Offset; var dr = new DebugReader(sym); var scope = dr.FindScopeSym(off); var vars = dr.FindVarSyms(off, scope).ToList(); var alls = new FastList <ElaValue[]>(); alls.AddRange(captures); alls.Add(locals); var count = alls.Count - 1; var locs = alls[count]; var ret = new List <TraceVar>(); do { for (var i = 0; i < vars.Count; i++) { var v = vars[i]; var val = locs[v.Address]; if (((ElaVariableFlags)v.Flags & ElaVariableFlags.CompilerGenerated) != ElaVariableFlags.CompilerGenerated) { ret.Add(new TraceVar(v.Name, val, locs == locals)); } } var ns = dr.GetScopeSymByIndex(scope.ParentIndex); if (ns.Index != scope.Index) { scope = ns; vars = dr.FindVarSyms(off, scope).ToList(); if (scope.RuntimeScope && count > 0) { locs = alls[--count]; } } else { scope = null; } }while (scope != null); return(ret); }
internal void Update(SortedBufferedDeletes @in) { numTerms += @in.numTerms; bytesUsed += @in.bytesUsed; terms.AddRange(@in.terms); terms.Sort(ref sorter); foreach (var term in @in.queries) { queries[term.Key] = term.Value; } docIDs.AddRange(@in.docIDs); @in.Clear(); }
/// <inheritdoc/> public bool UpdateChanges() { if (!HasChanged()) { return(false); } sortedKeys.Clear(); sortedKeys.AddRange(KeyFrames.ToArray()); sortedKeys.Sort(this); framesCount = KeyFrames.Count; for (var i = 0; i < framesCount; i++) { KeyFrames[i].HasChanged = false; } return(true); }
public void AssertThatRangeCanBeAdded() { var oneArray = new int[5]; for (var i = 0; i < oneArray.Length; i++) { oneArray[i] = 1; } _fastList.AddRange(oneArray); Assert.AreEqual(5, _fastList.Length); _fastList.AddRange(oneArray); Assert.AreEqual(10, _fastList.Length); _fastList.AddRange(oneArray); Assert.AreEqual(15, _fastList.Length); for (var i = 0; i < _fastList.Length; i++) { Assert.AreEqual(1, _fastList.buffer[i]); } }
/// <summary> /// Reorganizes internal data and resources to match the given objects, and append extra values at the end. /// </summary> /// <param name="collectionLayout"></param> public unsafe void UpdateLayout(ParameterCollectionLayout collectionLayout) { var oldLayout = this.layout; this.layout = collectionLayout; // Same layout, or removed layout if (oldLayout == collectionLayout || collectionLayout == null) { return; } var layoutParameterKeyInfos = collectionLayout.LayoutParameterKeyInfos; // Do a first pass to measure constant buffer size var newParameterKeyInfos = new FastList <ParameterKeyInfo>(Math.Max(1, parameterKeyInfos.Count)); newParameterKeyInfos.AddRange(parameterKeyInfos); var processedParameters = new bool[parameterKeyInfos.Count]; var bufferSize = collectionLayout.BufferSize; var resourceCount = collectionLayout.ResourceCount; foreach (var layoutParameterKeyInfo in layoutParameterKeyInfos) { // Find the same parameter in old collection // Is this parameter already added? for (int i = 0; i < parameterKeyInfos.Count; ++i) { if (parameterKeyInfos[i].Key == layoutParameterKeyInfo.Key) { processedParameters[i] = true; newParameterKeyInfos.Items[i] = layoutParameterKeyInfo; break; } } } // Append new elements that don't exist in new layouts (to preserve their values) for (int i = 0; i < processedParameters.Length; ++i) { // Skip parameters already processed before if (processedParameters[i]) { continue; } var parameterKeyInfo = newParameterKeyInfos[i]; if (parameterKeyInfo.Offset != -1) { // It's data newParameterKeyInfos.Items[i].Offset = bufferSize; var elementSize = newParameterKeyInfos.Items[i].Key.Size; var elementCount = newParameterKeyInfos.Items[i].Count; var totalSize = elementSize + (elementSize + 15) / 16 * 16 * (elementCount - 1); bufferSize += totalSize; } else if (parameterKeyInfo.BindingSlot != -1) { // It's a resource newParameterKeyInfos.Items[i].BindingSlot = resourceCount++; } } var newDataValues = new byte[bufferSize]; var newResourceValues = new object[resourceCount]; // Update default values var bufferOffset = 0; foreach (var layoutParameterKeyInfo in layoutParameterKeyInfos) { if (layoutParameterKeyInfo.Offset != -1) { // It's data // TODO: Set default value var defaultValueMetadata = layoutParameterKeyInfo.Key?.DefaultValueMetadata; if (defaultValueMetadata != null) { fixed(byte *newDataValuesPtr = newDataValues) defaultValueMetadata.WriteBuffer((IntPtr)newDataValuesPtr + bufferOffset + layoutParameterKeyInfo.Offset, 16); } } } // Second pass to copy existing data at new offsets/slots for (int i = 0; i < parameterKeyInfos.Count; ++i) { var parameterKeyInfo = parameterKeyInfos[i]; var newParameterKeyInfo = newParameterKeyInfos[i]; if (newParameterKeyInfo.Offset != -1) { var elementSize = newParameterKeyInfos.Items[i].Key.Size; var newTotalSize = elementSize + (elementSize + 15) / 16 * 16 * (newParameterKeyInfo.Count - 1); var totalSize = elementSize + (elementSize + 15) / 16 * 16 * (parameterKeyInfo.Count - 1); // It's data fixed(byte *dataValues = DataValues) fixed(byte *newDataValuesPtr = newDataValues) Utilities.CopyMemory((IntPtr)newDataValuesPtr + newParameterKeyInfo.Offset, (IntPtr)dataValues + parameterKeyInfo.Offset, Math.Min(newTotalSize, totalSize)); } else if (newParameterKeyInfo.BindingSlot != -1) { // It's a resource newResourceValues[newParameterKeyInfo.BindingSlot] = ObjectValues[parameterKeyInfo.BindingSlot]; } } // Update new content parameterKeyInfos = newParameterKeyInfos; DataValues = newDataValues; ObjectValues = newResourceValues; }
private Tuple <DynamicVao, DynamicVao> TryBuildVaoForLight(Light light) { _hullVertices.Clear(); _shadowVertices.Clear(); _shadowIndices.Clear(); _hullIndices.Clear(); int numSegments = 0; int shadowIndexOffset = 0; int hullIndexOffset = 0; int hullCount = _engine.Hulls.Count; for (int i = 0; i < hullCount; i++) { Hull hull = _engine.Hulls[i]; if (!hull.Enabled || !hull.Valid || light.IgnoredHulls.Contains(hull) || !light.Intersects(hull)) { continue; } Polygon points = hull.WorldPoints; Vector2 prevPoint = points[points.Count - 1]; int pointCount = points.Count; numSegments += pointCount; for (int j = 0; j < pointCount; j++) { Vector2 currentPoint = points[j]; _shadowVertices.Add(new VertexShadow(prevPoint, currentPoint, new Vector2(0.0f, 0.0f))); _shadowVertices.Add(new VertexShadow(prevPoint, currentPoint, new Vector2(1.0f, 0.0f))); _shadowVertices.Add(new VertexShadow(prevPoint, currentPoint, new Vector2(0.0f, 1.0f))); _shadowVertices.Add(new VertexShadow(prevPoint, currentPoint, new Vector2(1.0f, 1.0f))); _shadowIndices.Add(shadowIndexOffset * 4 + 0); _shadowIndices.Add(shadowIndexOffset * 4 + 1); _shadowIndices.Add(shadowIndexOffset * 4 + 2); _shadowIndices.Add(shadowIndexOffset * 4 + 1); _shadowIndices.Add(shadowIndexOffset * 4 + 3); _shadowIndices.Add(shadowIndexOffset * 4 + 2); prevPoint = currentPoint; shadowIndexOffset++; } _hullVertices.AddRange(hull.WorldPoints); int indexCount = hull.Indices.Count; for (int j = 0; j < indexCount; j++) { _hullIndices.Add(hull.Indices[j] + hullIndexOffset); } hullIndexOffset += pointCount; } if (numSegments == 0) { return(null); } Tuple <DynamicVao, DynamicVao> lightVaos; if (!_lightsVaos.TryGetValue(light, out lightVaos)) { lightVaos = Tuple.Create( DynamicVao.New(_engine.Device, VertexShadow.Layout, PrimitiveType.TriangleList, _shadowVertices.Count, _shadowIndices.Count, useIndices: true), DynamicVao.New(_engine.Device, VertexPosition2.Layout, PrimitiveType.TriangleList, _hullVertices.Count, _hullIndices.Count, useIndices: true)); _lightsVaos.Add(light, lightVaos); } lightVaos.Item1.SetVertices(_shadowVertices); lightVaos.Item1.SetIndices(_shadowIndices); lightVaos.Item2.SetVertices(_hullVertices); lightVaos.Item2.SetIndices(_hullIndices); return(lightVaos); }
internal CodeAssembly() { modules = new FastList<CodeFrame>(); foreignModules = new FastList<ForeignModule>(); moduleMap = new Dictionary<String,Int32>(); quals = new FastList<Boolean>(); Instances = new Dictionary<Int64,Byte>(); Constructors = new FastList<ConstructorData>(); Types = new FastList<TypeData> { new TypeData(ElaTypeCode.None), new TypeData(ElaTypeCode.Integer), new TypeData(ElaTypeCode.Long), new TypeData(ElaTypeCode.Single), new TypeData(ElaTypeCode.Double), new TypeData(ElaTypeCode.Boolean), new TypeData(ElaTypeCode.Char), new TypeData(ElaTypeCode.String), new TypeData(ElaTypeCode.Unit), new TypeData(ElaTypeCode.List), new TypeData(ElaTypeCode.__Reserved), new TypeData(ElaTypeCode.Tuple), new TypeData(ElaTypeCode.Record), new TypeData(ElaTypeCode.Function), new TypeData(ElaTypeCode.Object), new TypeData(ElaTypeCode.Module), new TypeData(ElaTypeCode.Lazy), new TypeData(ElaTypeCode.__Reserved2), new TypeData(ElaTypeCode.__Reserved3) }; Cls = new FastList<Class>(); Cls.AddRange( new Class[] { new Class(), //ERR new IntegerInstance(), //INT new LongInstance(), //LNG new SingleInstance(), //SNG new DoubleInstance(), //DBL new BooleanInstance(), //BYT new CharInstance(), //CHR new StringInstance(), //STR new UnitInstance(), //UNI new ListInstance(), //LST new Class(), //TAB new TupleInstance(), //TUP new RecordInstance(), //REC new FunctionInstance(), //FUN new Class(), //OBJ new ModuleInstance(), //MOD new Class(), //LAZ new Class(), //RES2 new Class(), //RES3 }); }
/// <summary> /// To the hx mesh nodes. /// </summary> /// <param name="mesh">The mesh.</param> /// <param name="scene">The scene.</param> /// <param name="transform"></param> /// <returns></returns> /// <exception cref="System.NotSupportedException">Mesh Type {mesh.Type}</exception> protected virtual HxScene.SceneNode OnCreateHxMeshNode(MeshInfo mesh, HelixInternalScene scene, Matrix transform) { switch (mesh.Type) { case PrimitiveType.Triangle: var material = scene.Materials[mesh.MaterialIndex]; var cullMode = material.Key.HasTwoSided && material.Key.IsTwoSided ? CullMode.Back : CullMode.None; if (Configuration.ForceCullMode) { cullMode = Configuration.CullMode; } var fillMode = material.Key.HasWireFrame && material.Key.IsWireFrameEnabled ? FillMode.Wireframe : FillMode.Solid; //Determine if has bones HxScene.MeshNode mnode; if (mesh.AssimpMesh.HasBones || mesh.AssimpMesh.HasMeshAnimationAttachments) { var mn = new HxScene.BoneSkinMeshNode(); //Bones if (mesh.AssimpMesh.HasBones) { mn.Bones = mesh.AssimpMesh.Bones.Select(x => new HxAnimations.Bone() { Name = x.Name, BindPose = x.OffsetMatrix.ToSharpDXMatrix(configuration.IsSourceMatrixColumnMajor).Inverted(), BoneLocalTransform = Matrix.Identity, InvBindPose = x.OffsetMatrix.ToSharpDXMatrix(configuration.IsSourceMatrixColumnMajor),//Documented at https://github.com/assimp/assimp/pull/1803 }).ToArray(); } else { mn.Geometry = mesh.Mesh; mn.SetupIdentitySkeleton(); } //Morph targets if (mesh.AssimpMesh.HasMeshAnimationAttachments) { int attCount = mesh.AssimpMesh.MeshAnimationAttachmentCount; var mtv = new FastList <MorphTargetVertex>(attCount * mesh.AssimpMesh.VertexCount); foreach (var att in mesh.AssimpMesh.MeshAnimationAttachments) { //NOTE: It seems some files may have invalid normal/tangent data for morph targets. //May need to provide option in future to use 0 normal/tangent deltas or recalculate mtv.AddRange(new MorphTargetVertex[mesh.AssimpMesh.VertexCount].Select((x, i) => new MorphTargetVertex() { deltaPosition = (att.Vertices[i] - mesh.AssimpMesh.Vertices[i]).ToSharpDXVector3(), deltaNormal = att.HasNormals ? (att.Normals[i] - mesh.AssimpMesh.Normals[i]).ToSharpDXVector3() : Vector3.Zero, deltaTangent = att.HasTangentBasis ? (att.Tangents[i] - mesh.AssimpMesh.Tangents[i]).ToSharpDXVector3() : Vector3.Zero })); } mn.MorphTargetWeights = new float[attCount]; mn.InitializeMorphTargets(mtv.ToArray(), mesh.AssimpMesh.VertexCount); } mnode = mn; } else { mnode = new HxScene.MeshNode(); } mnode.Name = string.IsNullOrEmpty(mesh.AssimpMesh.Name) ? $"{nameof(HxScene.MeshNode)}_{Interlocked.Increment(ref MeshIndexForNoName)}" : mesh.AssimpMesh.Name; mnode.Geometry = mesh.Mesh; mnode.Material = material.Value; mnode.ModelMatrix = transform; mnode.CullMode = cullMode; mnode.FillMode = fillMode; return(mnode); case PrimitiveType.Line: var lnode = new HxScene.LineNode { Name = string.IsNullOrEmpty(mesh.AssimpMesh.Name) ? $"{nameof(HxScene.LineNode)}_{Interlocked.Increment(ref MeshIndexForNoName)}" : mesh.AssimpMesh.Name, Geometry = mesh.Mesh, ModelMatrix = transform }; var lmaterial = new LineMaterialCore(); //Must create separate line material lnode.Material = lmaterial; var ml = scene.Materials[mesh.MaterialIndex].Value; if (ml is DiffuseMaterialCore diffuse) { lmaterial.LineColor = diffuse.DiffuseColor; } return(lnode); case PrimitiveType.Point: var pnode = new HxScene.PointNode { Name = string.IsNullOrEmpty(mesh.AssimpMesh.Name) ? $"{nameof(HxScene.PointNode)}_{Interlocked.Increment(ref MeshIndexForNoName)}" : mesh.AssimpMesh.Name, Geometry = mesh.Mesh, ModelMatrix = transform }; var pmaterial = new PointMaterialCore(); //Must create separate point material pnode.Material = pmaterial; var pm = scene.Materials[mesh.MaterialIndex].Value; if (pm is DiffuseMaterialCore diffuse1) { pmaterial.PointColor = diffuse1.DiffuseColor; } return(pnode); default: throw new NotSupportedException($"Mesh Type {mesh.Type} does not supported"); } }
private void BuildVaosForLight(Light light, LightVaos lightVaos) { _hullVertices.Clear(); _shadowVertices.Clear(); _shadowIndices.Clear(); _hullIndices.Clear(); int numSegments = 0; int shadowIndexOffset = 0; int hullIndexOffset = 0; int hullCount = _engine.Hulls.Count; for (int i = 0; i < hullCount; i++) { Hull hull = _engine.Hulls[i]; if (!hull.Enabled || !hull.Valid || light.IgnoredHulls.Contains(hull) || !light.Intersects(hull)) { continue; } Polygon points = hull.WorldPoints; Vector2 prevPoint = points.Items[points.Count - 1]; int pointCount = points.Count; numSegments += pointCount; for (int j = 0; j < pointCount; j++) { Vector2 currentPoint = points.Items[j]; _shadowVertices.Add(new VertexShadow(prevPoint, currentPoint, new Vector2(0.0f, 0.0f))); _shadowVertices.Add(new VertexShadow(prevPoint, currentPoint, new Vector2(1.0f, 0.0f))); _shadowVertices.Add(new VertexShadow(prevPoint, currentPoint, new Vector2(0.0f, 1.0f))); _shadowVertices.Add(new VertexShadow(prevPoint, currentPoint, new Vector2(1.0f, 1.0f))); _shadowIndices.Add(shadowIndexOffset * 4 + 0); _shadowIndices.Add(shadowIndexOffset * 4 + 1); _shadowIndices.Add(shadowIndexOffset * 4 + 2); _shadowIndices.Add(shadowIndexOffset * 4 + 1); _shadowIndices.Add(shadowIndexOffset * 4 + 3); _shadowIndices.Add(shadowIndexOffset * 4 + 2); prevPoint = currentPoint; shadowIndexOffset++; } _hullVertices.AddRange(hull.WorldPoints); int indexCount = hull.Indices.Count; for (int j = 0; j < indexCount; j++) { _hullIndices.Add(hull.Indices.Items[j] + hullIndexOffset); } hullIndexOffset += pointCount; } lightVaos.Enabled = numSegments > 0; if (!lightVaos.Enabled) { return; } if (lightVaos.ShadowVao == null) { lightVaos.ShadowVao = DynamicVao.New( _engine.Device, VertexShadow.Layout, PrimitiveType.TriangleList, _shadowVertices.Count, _shadowIndices.Count, useIndices: true); lightVaos.HullVao = DynamicVao.New( _engine.Device, VertexPosition2.Layout, PrimitiveType.TriangleList, _hullVertices.Count, _hullIndices.Count, useIndices: true); } lightVaos.ShadowVao.SetVertices(_shadowVertices); lightVaos.ShadowVao.SetIndices(_shadowIndices); lightVaos.HullVao.SetVertices(_hullVertices); lightVaos.HullVao.SetIndices(_hullIndices); }
public byte[] DownloadData() { Stopwatch sw = Stopwatch.StartNew(); try { if (_currentStream == null) { Trace.WriteLine("Connecting to " + _ip + " for " + _uri); _errored = false; _currentTcpClient = new TcpClient(); _currentTcpClient.NoDelay = true; _currentTcpClient.ReceiveTimeout = 500; _currentTcpClient.SendTimeout = 500; _currentTcpClient.Connect(_ip, _uri.Port); _currentStream = _currentTcpClient.GetStream(); _currentStream.ReadTimeout = 500; _currentStream.WriteTimeout = 500; byte[] initialBuffer = Encoding.ASCII.GetBytes(string.Format(_initialRequestFormat, _uri.ToString(), _uri.Host)); _currentStream.Write(initialBuffer, 0, initialBuffer.Length); //_readyNextRequest = Encoding.ASCII.GetBytes(string.Format(_nextRequestFormat, uri.ToString(), uri.Host)); _readyNextRequest = initialBuffer; } else { _currentStream.Write(_readyNextRequest, 0, _readyNextRequest.Length); } _responseBuffer.Clear(); int bytesRead; int bytesAnalyzed; bool endOfHeadersReached = false; int contentLength = -1; string httpVersion = null; do { bytesRead = _currentStream.Read(_buffer, 0, _buffer.Length); _responseBuffer.AddRange(_buffer, 0, bytesRead); IList <string> newHeaders = AnalyzeHeaders(_responseBuffer.GetInternalBuffer(), _responseBuffer.Count, out bytesAnalyzed, out endOfHeadersReached); _responseBuffer.RemoveRange(0, bytesAnalyzed); foreach (string header in newHeaders) { Trace.WriteLine(header); if (header.StartsWith("HTTP/1")) { string[] splitted = header.Split(_spaceCharArray); string httpResponseCode = splitted[1]; if (httpResponseCode != "200") { throw new InvalidDataException("httpResponseCode is " + httpResponseCode); } httpVersion = splitted[0]; } else if (header.StartsWith("Content-Length:")) { contentLength = int.Parse(header.Split(_spaceCharArray)[1]); } else if (header == "Connection: keep-alive") { _keepAlive = true; } else if (header == "Connection: close") { _keepAlive = false; } } }while (!endOfHeadersReached); if (contentLength < 0 && httpVersion != "HTTP/1.0") { throw new InvalidDataException("Content-Length is " + contentLength); } Trace.WriteLine("HTTP Version is " + httpVersion); if (httpVersion != "HTTP/1.0") { while (_responseBuffer.Count < contentLength) { bytesRead = _currentStream.Read(_buffer, 0, _buffer.Length); _responseBuffer.AddRange(_buffer, 0, bytesRead); } } else { _keepAlive = false; try { while ((bytesRead = _currentStream.Read(_buffer, 0, _buffer.Length)) > 0) { _responseBuffer.AddRange(_buffer, 0, bytesRead); } } catch (Exception) { } } byte[] result = _responseBuffer.ToArray(); return(result); } catch (Exception ex) { Trace.WriteLine("Connecting to " + _ip + " for " + _uri); Trace.WriteLine("Exception from " + _ip + " for " + _uri + ": " + ex.ToString()); _errored = true; _keepAlive = false; if (_currentStream != null) { _currentStream.Close(); _currentStream = null; } if (_currentTcpClient != null) { _currentTcpClient.Close(); _currentTcpClient = null; } throw; } finally { if (!_keepAlive) { if (_currentStream != null) { _currentStream.Close(); _currentStream = null; } if (_currentTcpClient != null) { _currentTcpClient.Close(); _currentTcpClient = null; } } Trace.WriteLine("DownloadData " + sw.Elapsed); } //HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); ////request.KeepAlive = true; ////request.IfModifiedSince = _lastModified; ////request.Host = "www.oref.org.il"; //using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) //{ // //_lastModified = response.LastModified; // using (Stream responseStream = response.GetResponseStream()) // using (StreamReader reader = new StreamReader(responseStream, Encoding.Unicode)) // { // return reader.ReadToEnd(); // } //} }