I have an sample application which send a TCP request to a server and the server returns a byte array. This is then saved to a memory stream for processing. The client appears to successfully save the byte array to the memory stream as when a break point is positioned int he code before it leaves the function the memory stream has data in it.
enum type
{
Audio,
Update
}
class NetworkObject
{
public TcpClient tcp;
public type ConnectionType;
public string URL;
public MemoryStream AudioMemoryStream;
}
private TcpClient tcpclientAudio = new TcpClient();
private NetworkObject audioObj = null;
private void button1_Click(object sender, EventArgs e)
{
if (tcpclientAudio.Connected)
tcpclientAudio.Close();
tcpclientAudio = new TcpClient();
string audioId = recordIdTextBox.Text.Trim();
string audioType = type.Audio.ToString();
string message = "GET /fred?id=" + audioId + "&live=false HTTP/1.1\r\n" + "Sec-WebSocket-Key: 4eW1rRpCzr60VdvY3lZZMw==\r\n";
audioObj = new NetworkObject();
audioObj.tcp = tcpclientAudio;
audioObj.ConnectionType = type.Audio;
audioObj.URL = message;
audioObj.AudioMemoryStream = new MemoryStream();
tcpclientAudio.BeginConnect(IPAddress.Parse("127.0.0.1"), 8008, new AsyncCallback(CallBackConnectMethod), audioObj);
}
void CallBackConnectMethod(IAsyncResult result)
{
NetworkObject obj = (NetworkObject)result.AsyncState;
TcpClient tcp = obj.tcp;
NetworkStream ns = tcp.GetStream();
byte[] buffer = new byte[2048];
int read = 0;
string message = obj.URL;
byte[] request = Encoding.ASCII.GetBytes(message);
ns.Write(request, 0, request.Length);
read = ns.Read(buffer, 0, 1000);
Console.WriteLine(Encoding.ASCII.GetString(buffer, 00, read));
obj.AudioMemoryStream = new MemoryStream();
do
{
try
{
read = ns.Read(buffer, 0, 1);
if (buffer[0] == 0x82)
{
read = ns.Read(buffer, 0, 1);
int len = 0;
switch (buffer[0])
{
case 126:
read = ns.Read(buffer, 0, 2);
len = (buffer[0] << 8) + buffer[1];
break;
default:
len = buffer[0];
break;
}
read = ns.Read(buffer, 0, len);
if (obj.ConnectionType == type.Update)
Console.WriteLine(Encoding.ASCII.GetString(buffer, 0, read));
else
{
obj.AudioMemoryStream.Write(buffer, 0, read);
}
}
else
{
ns.Close();
read = 0;
}
}
catch (Exception)
{
read = 0;
}
}
while (read > 0);
Debug.WriteLine("Just leaving");
}
What I have tried:
Initially the memory stream was not in the NetworkObject class but this was added as it is defined outside the thread and passed in. As it is initialised and populated with the thread I hoped it would still be available on the main thread once it had been populated.