2016-03-03 112 views
0

我需要翻譯此代碼以添加大字節2字節標題。它現在沒有標題,但我在添加它方面有點失落。將標題添加到服務器/客戶端連接

TcpClient client = new TcpClient(ipNum, portNum); 
NetworkStream nw = client.GetStream(); 
byte[] send = Encoding.UTF8.GetBytes(userInput); 

Console.WriteLine("Sending : " + userInput); 
nw.Write(send, 0, send.Length); 

byte[] readBytes = new byte[client.ReceiveBufferSize]; 
int bytesRead = nw.Read(readBytes, 0, client.ReceiveBufferSize); 
Console.WriteLine("Received : " + Encoding.UTF8.GetString(readBytes 0, readBytes); 
+0

做一個谷歌搜索'添加頭到tcp客戶端'同時檢查了這一點 - http://stackoverflow.com/questions/19523088/create-http-request-using-tcpclient – MethodMan

回答

1

UTF8Encoding支持添加該報頭。手動實例化該類,並使用允許指定需要BOM標頭的構造函數。

請注意,您的閱讀代碼已損壞,因爲您可能會收到來自遠程端的少於一條「消息」。您一次只能收到一個字節。 client.ReceiveBufferSize也沒有意義。只需選擇一個靜態緩衝區大小,如4096