2016-11-29 56 views
-2


我是C#中的新成員,我在C#中的文本框中出現了方形白色字符的問題。 (見下面的屏幕截圖)
我已經實現了System.Net.Sockets.支持的用於聊天的客戶端 - 服務器程序每個程序的內部都是byte[] array= new byte[10025],它永遠不會滿滿,但是文本框裏面會顯示空白字符。你能幫我刪除這些字符嗎?
謝謝!客戶端的

Blank white character squares白色字符C#文本框

讀碼:
http://pastebin.com/W3Pc3BPG

 try 
     { 
      while (true) 
      { 
       serverStream = clientSocket.GetStream(); 
       int buffSize = 0; 
       byte[] inStream = new byte[10025]; 
       buffSize = clientSocket.ReceiveBufferSize; 
       serverStream.Read(inStream, 0, inStream.Length); 
       string returndata = System.Text.Encoding.UTF8.GetString(inStream); 
       readData = "" + returndata; 
       msg(); 
      } 
     } catch(Exception e) 
     { 
      ctThread.Join(); 
     } 
+4

當從套接字中讀取,從'Read'方法的返回將是包含你讀取的字節數的整數。你*必須*尊重這個數字 - 數組中其餘的字符將是垃圾。如果你用你的套接字閱讀代碼更新了帖子,我們可以建議合適的修正(但基本上,它是「只從數組中獲取正確數量的字符) –

+1

你有一個編碼問題。如果你正在使用Textbox替換RichTextBox如果你使用任何流,請確保編碼是UTF8,默認是ASCII,它將改變非打印字符,你也可能有Unicode字符,可能需要使用Unicode(而不是UTF8) – jdweng

+0

你可以發佈代碼你的通信程序? –

回答

2
serverStream = clientSocket.GetStream(); 
int buffSize = 0; 
byte[] inStream = new byte[10025]; 
buffSize = clientSocket.ReceiveBufferSize; 
// Make sure you respect the number of bytes that have been read. 
// Note that the below code is not the most performant - it's just 
// to demonstrate the technique. 
int bytesRead = serverStream.Read(inStream, 0, inStream.Length); 
byte[] theData = inStream.Take(bytesRead).ToArray(); 
string returndata = System.Text.Encoding.UTF8.GetString(theData); 
readData = "" + returndata; 
msg(); 
+0

再次感謝您!現在我明白了,一切都很完美。 – ZPA

0

您可以使用下面的代碼的文本框,以檢查是否是空白。

bool hasAllWhitespace = txtBox1.Text.Length>0 && 
         txtBox1.Text.Trim().Length==0; 

爲了消除空間

if (hasAllwhitespace) 
{ 
    txtBox1.Text.Trim(); 
}