public Frame ReadData() { Frame frame = new Frame(new byte[] { }); IAsyncResult result = Client.Stream.BeginRead(Client.InputData, 0, Client.InputData.Length, null, Client); if (result != null) { int bytesRead = Client.Stream.EndRead(result); if (bytesRead > 0) { frame = new Frame(WebSocketUtil.SubArray(Client.InputData, 0, bytesRead)); ProcessReceivedData(frame); WebSocketUtil.LogVerbose("Client {0:D3}: Read Type {1} : {2} ", Client.Id, frame.FrameType, frame.Content.Length); } } return(frame); }
public void ReadDataCallback(IAsyncResult result) { Client client = (Client)result.AsyncState; if (client.IsDisposed) { return; } int bytesRead = client.Stream.EndRead(result); // wait until the buffer is filled int bytesReadIntotal = bytesRead; ArrayList InputDataArray = new ArrayList(); byte[] tempBuffer = null; if (bytesRead > 0) { tempBuffer = WebSocketUtil.SubArray(Client.InputData, 0, bytesRead); // start looping if there is still remaining data if (client.TcpClient.GetStream().DataAvailable) { // add the first buffer to the arrayList InputDataArray.Add(tempBuffer); // start looping appending to the arrayList while (client.TcpClient.GetStream().DataAvailable) { bytesRead = client.TcpClient.GetStream().Read(Client.InputData, 0, Client.InputData.Length); tempBuffer = WebSocketUtil.SubArray(Client.InputData, 0, bytesRead); InputDataArray.Add(tempBuffer); bytesReadIntotal += bytesRead; WebSocketUtil.LogVerbose("Looping: Client {0:D3}: bytesReadHere {1} ", Client.Id, bytesRead); } // create a single byte array with the arrayList tempBuffer = new byte[bytesReadIntotal]; int arrayIndex = 0; foreach (byte[] item in InputDataArray.ToArray()) { for (int i = 0; i < item.Length; i++) { tempBuffer[arrayIndex] = item[i]; arrayIndex++; } } } // Create frame with the tempBuffer Frame frame = new Frame(tempBuffer); WebSocketUtil.LogVerbose("Client {0:D3}: Read Type {1} : {2} ", Client.Id, frame.FrameType, bytesReadIntotal); ProcessReceivedData(frame); // Send Pong if the frame was Ping if (frame.FrameType == FrameType.Ping) { SendPong(frame); } if (client.IsDisposed) { return; } // Start the Async Read to handle the next frame comming from server client.Stream.BeginRead(client.InputData, 0, client.InputData.Length, ReadDataCallback, client); } else { client.Dispose(); } }