2012-06-02 205 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说。