Last active
December 28, 2015 19:09
-
-
Save killnine/7548451 to your computer and use it in GitHub Desktop.
Trying to use a mock NetworkStream to fake out some data that would normally come over a network device. I want to make sure my test works without being dependent on outside piece of hardware.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ABEthernetDriver | |
{ | |
/* Some other methods and properties, constructor */ | |
private ITcpClient _client; | |
private INetworkStream _nstream; | |
public void Connect() | |
{ | |
_nstream = _client.GetStream(); | |
byte[] numArray = new byte[] {1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; | |
_responded[0] = false; | |
try | |
{ | |
//Signature: IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, object state) | |
_nstream.BeginRead(_readBuffer, 0, checked(_readBuffer.Length), DataReceived, _nstream); | |
_nstream.Write(numArray, 0, checked(numArray.Length)); | |
} | |
catch (Exception ex) | |
{ | |
_log.ErrorFormat("Unable to connect to device at: {0}", ex.Message); | |
throw; | |
} | |
} | |
private void DataReceived(IAsyncResult ar) | |
{ | |
try | |
{ | |
_bytecount = _nstream.EndRead(ar); | |
if (_bytecount == 0) | |
{ | |
bool dataAvailable = _nstream.DataAvailable; | |
} | |
_receivedDataPacket.Clear(); | |
int num = checked(_bytecount - 1); | |
for (int i = 0; i <= num; i++) | |
{ | |
_receivedDataPacket.Add(_readBuffer[i]); | |
} | |
ProcessReceivedData(); | |
} | |
catch (Exception ex) | |
{ | |
_log.ErrorFormat("DataReceived failed to parse data: {0}", ex.Message); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment