2012-06-02 202 views
1

我有一個客戶端,它給了我一個非SSL的URL:端口發送信息(包含XML數據的字符串)到他們的服務器。我用油灰(Telnet方式)成功地與服務器進行通信,並收到回覆,但是當我使用下面的代碼沒有通信由套接字通信失敗

outputmsg = string.Empty; 
       var m_socListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP); 
       IPHostEntry ipAddress = Dns.GetHostEntry("testurlhere"); 
       var ip = new IPEndPoint(ipAddress.AddressList[0], 10121); 
       m_socListener.Connect(ip); 

       byte[] tosend = GetBytes(inputmsg); 
       byte[] buffer = new byte[1024]; 
       m_socListener.Send(tosend); // doesnt sends data and returns immediately 
       m_socListener.Receive(buffer); // waits forever 
       m_socListener.Close(); 



static byte[] GetBytes(string str) 
     { 
      byte[] bytes = new byte[str.Length * sizeof(char)]; 
      System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length); 
      return bytes; 
     } 

    static string GetString(byte[] bytes) 
    { 
     char[] chars = new char[bytes.Length/sizeof(char)]; 
     System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length); 
     return new string(chars); 
    } 
+1

問:你確定「沒有任何東西發送到服務器」?例如,服務器可能正在等待「\ n」(並且您未能在「inputmsg」中發送一個)。有許多可能的情況。絕對檢查客戶端上的錯誤;絕對要檢查你在服務器上收到的是什麼 - 如果有的話。絕對要檢查它們之間的防火牆。 – paulsm4

+1

是的,我讓他們檢查了日誌,沒有發現任何命中的服務器。 – logeeks

+1

如果沒有任何內容發送到服務器,那麼可能tosend沒有任何內容。如果您嘗試從字符串獲取字節,請使用[Encoding.GetBytes](http://msdn.microsoft.com/en-us/library/system.text.encoding.getbytes.aspx) – 3aw5TZetdf

回答

0

的解決辦法是在我的情況下,使用正確的編碼是ASCII和\ n附加到消息paulsm4說。