我目前有點卡住了我的C#項目。網絡流量 - 讀取數量每個讀取
我有2個應用程序,它們都具有一個共同的類定義我稱之爲NetMessage
一個NetMessage包含一個消息類型字符串屬性,以及2名清單列表。 我的想法是,我可以用類來打包這個類,並將數據作爲字節[]在網絡上發送。
因爲網絡流不會公佈他們接收的數據量,所以我修改了Send方法,以便在實際的byte []之前發送NetMessage byte []的大小。
private static byte[] ReceivedBytes(NetworkStream MainStream)
{
try
{
//byte[] myReadBuffer = new byte[1024];
int receivedDataLength = 0;
byte[] data = { };
long len = 0;
int i = 0;
MainStream.ReadTimeout = 60000;
//MainStream.CanTimeout = false;
if (MainStream.CanRead)
{
//Read the length of the incoming message
byte[] byteLen = new byte[8];
MainStream.Read(byteLen, 0, 8);
len = BitConverter.ToInt64(byteLen, 0);
data = new byte[len];
//data is now set to the appropriate size for the expected message
//While we have not got the full message
//Read each individual byte and append to data.
//This method, seems to work, but is ridiculously slow,
while (receivedDataLength < data.Length)
{
receivedDataLength += MainStream.Read(data, receivedDataLength, 1);
}
//receivedDataLength += MainStream.Read(data, receivedDataLength, data.Length);
return data;
}
}
catch (Exception E)
{
//System.Windows.Forms.MessageBox.Show("Exception:" + E.ToString());
}
return null;
}
我試圖將下面的大小參數更改爲類似於1024或data.Length,但我得到時髦的結果。 receivedDataLength + = MainStream.Read(data,receivedDataLength,1);
將其設置爲data.Length似乎會導致問題,當正在發送的類是幾MB的大小。 將緩衝區大小設置爲1024,就像我在其他示例中看到的那樣,當傳入郵件的大小很小時(例如843字節)會導致失敗,但它錯誤地表明我嘗試讀出界限或其他內容。
以下是用於首先發送數據的方法的類型。
public static void SendBytesToStream(NetworkStream TheStream, byte[] TheMessage)
{
//IAsyncResult r = TheStream.BeginWrite(TheMessage, 0, TheMessage.Length, null, null);
// r.AsyncWaitHandle.WaitOne(10000);
//TheStream.EndWrite(r);
try
{
long len = TheMessage.Length;
byte[] Bytelen = BitConverter.GetBytes(len);
TheStream.Write(Bytelen, 0, Bytelen.Length);
TheStream.Flush();
// <-- I've tried putting thread sleeps in this spot to see if it helps
//I've also tried writing each byte of the message individually
//takes longer, but seems more accurate as far as network transmission goes?
TheStream.Write(TheMessage, 0, TheMessage.Length);
TheStream.Flush();
}
catch (Exception e)
{
//System.Windows.Forms.MessageBox.Show(e.ToString());
}
}
我想讓這兩種方法設置到他們可靠地發送和接收數據的地步。 我使用的應用程序監視遊戲目錄中的截圖文件夾,當它檢測到TGA格式的屏幕截圖時,它會將其轉換爲PNG,然後將其字節[]發送到接收器。 接收器然後將其發佈到Facebook(我不希望我的FB令牌分佈在我的客戶端應用程序中),因此是服務器/代理的想法。 它很奇怪,但是當我單步執行代碼時,轉移總是成功的。 但是如果我全速運行它,沒有斷點,它通常會告訴我連接已被遠程主機關閉等。 客戶端通常幾乎立即完成發送數據,即使它是一個4mb文件。 接收者花費大約2分鐘從網絡流中讀取數據,如果客戶端完成數據發送,這是否意味着數據剛剛在網絡空間中浮動,並被拉下來,這無意義? 當然它應該是同步的?