2014-04-04 47 views
0

我使用Telnet協議從服務器PC讀取文本文件。但是當我嘗試將網絡流轉換爲刺激時,它會給出一些垃圾值。這裏會有什麼問題?將網絡流轉換爲字符串時獲取垃圾值

NetworkStream ns = tcpclient.GetStream(); 
StreamReader streamReader = new StreamReader(ns); 
StreamWriter streamWriter = new StreamWriter(ns); 
byte[] bytes = new byte[tcpclient.ReceiveBufferSize]; 
int bytesread = tcpclient.ReceiveBufferSize; 
ns.Read(bytes, 0, bytesread); 
string returndata = Encoding.ASCII.GetString(bytes); 

我試圖通過命令提示符讀取文本文件。使用以下步驟 1.在我的電腦中啓用服務器pc和客戶端中的telnet服務器。 2.將服務器pc中的telnet端口更改爲24 3.使用telnet命令連接到服務器pc。 4.從telnet窗口中使用>使用類型在命令提示符下顯示文本文件的內容。

現在我想從我的C#代碼做同樣的事情。我寫了下面的代碼:

TcpClient tcpclient = new TcpClient(); 
tcpclient.Connect(<ip address>, <port>); 
NetworkStream ns = tcpclient.GetStream(); 
StreamReader streamReader = new StreamReader(ns); 
byte[] msg = Encoding.ASCII.GetBytes("type <file location>"); 
string returnd = Encoding.ASCII.GetString(msg); 
ns.Write(msg, 0, msg.Length); 
StreamWriter streamWriter = new St 
byte[] bytes = new byte[tcpclient.ReceiveBufferSize]; 
int bytesread = tcpclient.ReceiveBufferSize; 
ns.Read(bytes, 0, bytesread);reamWriter(ns); 
string returndata = Encoding.ASCII.GetString(bytes); 

,但我的代碼總是給喜歡「YY%ÿûÿûÿý'ÿýÿý」一些垃圾輸出

+1

試圖轉換之前嘗試通過服務器發送的數據流的Base64編碼解碼成串。 –

+0

嘗試了Base64解碼,但輸出仍然只是垃圾。 – ash001

回答

0

ReceiveBufferSize是接收緩衝區的大小,但是當你讀,你並不總是獲得一個完整的緩衝區。該Read方法返回的實際字節數中讀取的,你應該用它來限制緩衝區的部分要進行解碼:

byte[] bytes = new byte[tcpclient.ReceiveBufferSize]; 
int nRead = ns.Read(bytes, 0, tcpclient.ReceiveBufferSize); 
string returndata = Encoding.ASCII.GetString(bytes, nRead); 
+0

上面的代碼可以幫助我過濾掉緩衝區中的空值,但仍然會給解碼後的字符串賦予垃圾值。 – ash001

相關問題