2013-09-16 61 views
0

我正在學習http://www.daveoncsharp.com/2009/08/csharp-chat-application-over-asynchronous-udp-sockets-part-1教程中的一個聊天應用程序。但是我有一個問題,任何人都可以解釋爲什麼我們在「Packet class」中知道「dataIdentifier」的「size in bytes」是4,「name length」是4,我在包類的頂部看到描述,但是我不知道爲什麼。而這些:聊天應用程序中的數據包的C#問題UDP

this.dataIdentifier =(DataIdentifier)BitConverter.ToInt32(dataStream,0); //我們將從dataStream的索引0轉換,但它如何知道結束?

int nameLength = BitConverter.ToInt32(dataStream,4); //爲什麼我們知道它從4開始?

非常感謝你和我的英語對不起。

回答

0

當您處理網絡通信時,您必須定義一個「協議」來定義您的「消息」,因爲網絡連接是Stream based not Message based

所以在protocal被定義爲以下

 
Description -> |dataIdentifier|name length|message length| name | message | 
Size in bytes -> |  4  |  4  |  4  |name length|message length| 

int永遠是System.Int32System.Int32將始終以4個字節存儲(除以8 32,你會得到4)。

這裏是在每列的數據類型的另一條線,也許這將幫助你

 
Description -> |dataIdentifier|name length|message length| name | message | 
Size in bytes -> |  4  |  4  |  4  |name length|message length| 
Data Type  -> |  int  | int |  int  | string | string | 

所以,現在我們爲什麼要跳過位轉換器4個字節。

讓我們把架構回來了,但這次我會,但數量下降表明

現在最後兩個「特別」的長度是不固定的長度,如前3個字節的數量,他們做了什麼從以前的專欄拿這個值是多少字節被讀取。

 
Description -> |dataIdentifier|name length|message length|    name    |      message            | 
Size in bytes -> |  4  |  4  |  4  |   name length   |     message length           | 
Bytes   -> |0 1 2 3  | 4 5 6 7 | 8 9 10 11 | 12 through (12 + name length) | (12 + name length) + 1 through ((12 + name length) + 1 + message length) | 

所以你可以看到在指數0閱讀dataIdentifier我們開始讀4個字節(這是多少BitConverter.ToInt32會讀) 。然後,當我們要讀取nameLength我們需要指數4開始,然後讀取其他4個字節,這就是爲什麼BitConverter.ToInt32傳遞4(和messageLength將被傳遞8)

如果有什麼不明確的,請在這麼說評論,我會詳細說明。

+0

非常感謝,我已經理解了這個問題! – thanh

+0

請問,請問我是枚舉類型還是int類型都需要4個字節來存儲? – thanh

+0

這一切都取決於如何定義枚舉,默認情況下枚舉存儲爲一個'int',但看看[文檔](http://msdn.microsoft.com/en-us/library/sbbt4032 .aspx)「*每個枚舉類型都有一個基礎類型,它可以是除char之外的任何整型。枚舉元素的默認基礎類型是int。要聲明另一個整型的枚舉(如byte),請在標識符後跟類型... *「如果他們使用默認值如果int和int值需要4個字節來存儲,那麼yes是一個枚舉需要4個字節(如果他們使用int作爲後盾) –