[英]How do you fill a Byte header with empty characters?
我目前正在嘗試將其他字節添加到字節數組。
我試圖將標頭發送到包含計算機名稱的服務器。 但是,由於計算機名稱可能會因嘗試創建一個特定長度(如100個字節)的字節數組的每台計算機而改變。
這意味着一旦我有了字符串頭“rdmstream§” + Dns.GetHostName()”,我就需要在末尾添加x字節的字節數或作為填充開始,因此總字節數= 100。
我想知道這是否可能?
以下是我的代碼的示例,該代碼具有設置的標頭長度:
public static void SendMultiScreen(byte[] img)
{
try
{
//string command = ("rdmstream§" + Dns.GetHostName()); //This is what I want to add.
byte[] send = new byte[img.Length + 16]; //Create a new buffer to send to the server
byte[] header = Encoding.Unicode.GetBytes("rdmstrea"); //Get the bytes of the header
Buffer.BlockCopy(header, 0, send, 0, header.Length); //Copy the header to the main buffer
fps = 800;
Buffer.BlockCopy(img, 0, send, header.Length, img.Length); //Copy the image to the main buffer
_clientSocket.Send(send, 0, send.Length, SocketFlags.None); //Send the image to the server
}
如您所見,只要消息只有8個字符,就可以正常工作。 但是我希望消息中的字符是可變的。
如果我說實話,我對字節沒有太多了解,所以我們將不勝感激。
先感謝您。
如果填充是正確的方法,人們可以爭論一下,但是您可以填充主機名
string hostName = "OhWhatEver".PadRight(100)
然后將其用作您的GetBytes調用的輸入。
編輯:如果您不能忍受空格,請使用:
byte[] header = new byte[100];
byte[] hostname = System.Text.Encoding.Unicode.GetBytes("rdmstream§" + System.Net.Dns.GetHostName());
Array.Copy(hostname, header, hostname.Length);
如果您擔心數據包碎片: Socket
有重載,可以在單個操作中發送緩沖區段列表 。 這意味着您可以執行以下操作:
var segments = new List<ArraySegment<byte>>();
segments.Add(header);
segments.Add(img);
請注意,標頭不必是完整數組; 您可以發送數組的一部分,從而允許您重復使用相同的緩沖區; 例如:
byte[] buffer = new byte[MaxLength];
var segments = new List<ArraySegment<byte>>();
segments.Add(default); // placeholder
segments.Add(img);
foreach(...) {
string val = ...
int len = encoding.GetBytes(val, 0, val.Length, buffer, 0);
segments[0] = new ArraySegment<byte>(buffer, 0, len);
thisSocket.Send(segments);
}
然而! 為此,通常需要在標頭上進行某種形式的構架-標記值(可能是末尾CR / LF / CRLF),或者是字符串的字節數前綴len
。
如果確實不可能...只需遍歷數組未使用的部分,並將其設置為Array.Clear
如果零為OK,則使用Array.Clear
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.