2016-10-12 28 views
0

我有一個從緩衝區中獲取數據,並將其轉換爲字符串,你可以看到一個功能:在c#中獲得unicode緩衝區字節返回'??????'

public string GetParameters(byte[] buf) 
{ 
    string result = System.Text.UnicodeEncoding.Unicode.GetString(buf); 
    return result; 
} 

另一個應用程序發送Farsi字符串來緩衝和我的應用程序應該得到這個數據,但我的應用程序的函數返回這個:

㨲께裙듘�����¯ 

爲什麼? enter image description here

我怎麼能接受的所有數據: 我定義的:

public byte[] dataBuffer = new byte[4000]; 

我有這樣的功能:

public void WaitForData(System.Net.Sockets.Socket soc) 
     { 
      try 
      { 
       if (pfnWorkerCallBack == null) 
       { 
        // Specify the call back function which is to be 
        // invoked when there is any write activity by the 
        // connected client 
        pfnWorkerCallBack = new AsyncCallback(OnDataReceived); 
       } 
       SocketPacket theSocPkt = new SocketPacket(); 
       theSocPkt.m_currentSocket = soc; 
       // Start receiving any data written by the connected client 
       // asynchronously 
       soc.BeginReceive(theSocPkt.dataBuffer, 0, 
            theSocPkt.dataBuffer.Length, 
            SocketFlags.None, 
            pfnWorkerCallBack, 
            theSocPkt); 
      } 
      catch (Exception qqq) 
      { 

      } 

     } 

而另一個問題:

public void OnDataReceived(IAsyncResult asyn) 
     { 
      try 
      { 
       SocketPacket socketData = (SocketPacket)asyn.AsyncState; 

       int iRx = 0; 
       // Complete the BeginReceive() asynchronous call by EndReceive() method 
       // which will return the number of characters written to the stream 
       // by the client 
       iRx = socketData.m_currentSocket.EndReceive(asyn); 
       string res = GetParameters(socketData.dataBuffer); 
} 
+0

使用'UTF32'而不是'Unicode' –

+2

恰好4k字節是一個可疑的整數。您只需要解碼具有數據的緩衝區的部分。 –

+0

@ M.kazemAkhgary utf32返回: –

回答

2

嘗試使用UTF-8:

string result = System.Text.UnicodeEncoding.UTF8.GetString(buf); 

這看起來像波斯語給我。 (但我不會說波斯語)

Unicode和UTF-8之間的差異這裏提到:UTF-8 vs. Unicode

基本上是一個字符的長度產生變化。

+0

你的工作 –

+0

它說波斯語只是خوشآمدید,這意味着歡迎英語:) –

+1

@EhsanAkbar很高興我能幫助你。 :-) – haindl

-1

string myDecodedString = Encoding.GetEncoding("1256").GetString(buf)

+0

{「'1256'不是受支持的編碼名稱。有關定義自定義編碼的信息,請參閱Encoding.RegisterProvider方法的文檔。\ r \ n參數名稱:name」} –

相關問題