locked
sending xml request via TCPClient takes long to receive response. RRS feed

  • Question

  • User767034699 posted

    Good day guys,

    i have a problem where im trying to connect to a host using the ip address provided, but i cant seem to be able to get a response from it.

        try
                    {
                        Socket serverSock = new Socket(
                     AddressFamily.InterNetwork,
                     SocketType.Stream,
                     ProtocolType.Tcp);
    
    
        IPAddress serverIP = IPAddress.Parse("");
                      IPEndPoint serverEP = new IPEndPoint(serverIP, port);
             Byte[] data = System.Text.Encoding.ASCII.GetBytes(postData);
    
    
    
                        NetworkStream stream = client.GetStream();
    
                        stream.Write(data, 0, data.Length);
    
                        Console.WriteLine("Sent: {0}", postData);
    
                        data = new Byte[256];
    
                        String responseData = String.Empty;
    
    
       SocketPermission perm = new SocketPermission(NetworkAccess.Accept, TransportType.Tcp, "", port);
                        Int32 bytes = stream.Read(data, 0, data.Length);
                        responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
                        Console.WriteLine("Received: {0}", responseData);
    
    
                        stream.Close();
                        client.Close(); 
    
       }
                    catch (Exception)
                    {
    
                        throw;
                    }     
    
    
    

    after that i will capture the response and load it into xml document. But im not receiving any response at all. it as it its hanging...

    kind regards

    Tony

    Friday, March 29, 2019 12:30 PM

All replies

  • User-893317190 posted

    Hi tonyR6 ,

    Your code is confusing , you initialize new Socket  and never use it.

    You also use 

      IPAddress serverIP = IPAddress.Parse("");
                      IPEndPoint serverEP = new IPEndPoint(serverIP, port);
             Byte[] data = System.Text.Encoding.ASCII.GetBytes(postData);

    After you haven't use the data, and set it to another value.

      data = new Byte[256];

    You also use  SocketPermission perm = new SocketPermission(NetworkAccess.Accept, TransportType.Tcp, "", port);, but I couldn't find where you use it.

    I find  you use client to GetStream , and call its Write methods to send data to server.

    Finally, you use System.Text.Encoding.ASCII.GetString(data, 0, bytes); to get response data.

    You could refer to the link below to learn how to use tcpclient ?

    https://docs.microsoft.com/en-us/dotnet/api/system.net.sockets.tcpclient?view=netframework-4.7.2

    I  also see you throw the exception , have you debug to see if any exception occurs?

    Do you have connection with your server? 

    Dose your server accept tcp request?

    Best regards,

    Ackerly Xu

    Monday, April 1, 2019 3:30 AM
  • User767034699 posted

    Hi there Ackerly,

    thanks for the response,

    i have changed the code now and use one of the examples provided, but i dont get any response back.

      try
               {
                   // Create a TcpClient.
                   // Note, for this client to work you need to have a TcpServer 
                   // connected to the same address as specified by the server, port
                   // combination.
                   //Int32 port = 13000;
                   TcpClient client = new TcpClient(server, port);
    
                   // Translate the passed message into ASCII and store it as a Byte array.
                   Byte[] data = System.Text.Encoding.ASCII.GetBytes(postData);
    
                   // Get a client stream for reading and writing.
                   //  Stream stream = client.GetStream();
    
                   NetworkStream stream = client.GetStream();
    
                   // Send the message to the connected TcpServer. 
                   stream.Write(data, 0, data.Length);
    
                   Console.WriteLine("Sent: {0}", postData);
    
                   // Receive the TcpServer.response.
    
                   // Buffer to store the response bytes.
                   data = new Byte[256];
    
                   // String to store the response ASCII representation.
                   String responseData = String.Empty;
    
                   // Read the first batch of the TcpServer response bytes.
                   Int32 bytes = stream.Read(data, 0, data.Length);
                   responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
                   Console.WriteLine("Received: {0}", responseData);
    
                   // Close everything.
                   stream.Close();
                   client.Close();
    
    
               }
    
    
    
               catch (Exception)
               {
    
                   throw;
               }

    kind regards

    Tony

    Monday, April 1, 2019 7:24 AM
  • User-893317190 posted

    Hi tonyR6 ,

    It also  depends on your server, how does your server  write?

    Best regards,

    Ackerly Xu 

    Monday, April 1, 2019 7:57 AM
  • User767034699 posted

    Hi there Ackerly,

    actually im still developing the service. Currently im on my local machine.

    kind regards

    Tony

    Monday, April 1, 2019 8:04 AM
  • User-893317190 posted

    Hi tonyR6,

    Yes , actually if you don't have a server that receives your tcpclient's message and send back message,  you won't receive message at your client side.

    Best regards,

    Ackerly Xu 

    Tuesday, April 2, 2019 1:17 AM
  • User767034699 posted

    Hi there Ackerly,

    but its very strange hey, when i telnet via cmd im able to send the xml request and receive the response. on c# part im not even able to receive the response. i even changed the code to handle some errors. and it shows that im successfully connected to the host ip.

          byte[] tData = Encoding.ASCII.GetBytes(tPostData);
                   using (TcpClient tClient = new TcpClient(server, port))
                   {
                       //if(tClient.Connected)
                       //{
                       //    tClient.EndConnect();
                       //}
                       //tClient.Connect(tServer, tPort);
    
                       SocketError tError;
                       // Send message
                       tClient.Client.Send(tData, 0, tData.Length, SocketFlags.None, out tError);
                       //XmlDocument xmlDocument = new XmlDocument();
                       using (Stream tStream = tClient.GetStream())
                       {
                           // Get length of response stream
    
                           byte[] tReponse = new byte[256];
                           // Read the first batch of the TcpServer response bytes.
    
                           int tBytes = tStream.Read(tReponse, 0, tData.Length);
    
                           var tResponseStr = System.Text.Encoding.ASCII.GetString(tReponse, 0, tReponse.Length);
    
                           Console.WriteLine("Received: {0}", tResponseStr);
                       }
                   }

    kind regards

    Tony

    Tuesday, April 2, 2019 10:39 AM
  • User-893317190 posted

    Hi tonyR6,

    Do you send request in cmd through curl?

    If so, maybe the connection between your client and server is not only through tcp.

    You could try to use http client like webrequest or httpclient to send a http request to see whether it solves your problem.

    https://docs.microsoft.com/en-us/dotnet/api/system.net.webrequest?view=netframework-4.7.2

    https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netframework-4.7.2

    Best regards,

    Ackerly Xu

    Wednesday, April 3, 2019 1:10 AM
  • User767034699 posted

    Hi there Ackerly,

    thanks for the response,

    im sending request to an ip address with a port. I have confirmed with the guys that we doing integrations with. on the ip address/server there's no webservice running on it. on the cmd im not using curl. actually they asked me to test through telnet on cmd.  e.g telnet server on port. then it opened telnet, pasted the xml request and hit enter. it responsed with response.

    so im not sure how to go about it on .net side cause im able to connect and send the request but not able to receive a response. Let me attach the network log...

    System.Net.Sockets Verbose: 0 : [21440] Entering TcpClient#60800190::TcpClient(196.38.158.118)
    System.Net.Sockets Verbose: 0 : [21440] Entering TcpClient#60800190::Connect(196.38.158.118)
    System.Net.Sockets Verbose: 0 : [21440] Entering DNS::GetHostAddresses(196.38.158.118)
    System.Net.Sockets Verbose: 0 : [21440] Exiting DNS::GetHostAddresses() 	-> IPAddress[]#9779853
    System.Net.Sockets Verbose: 0 : [21440] Entering Socket#65429669::Socket(AddressFamily#2)
    System.Net.Sockets Verbose: 0 : [21440] Exiting Socket#65429669::Socket() 
    System.Net.Sockets Verbose: 0 : [21440] Entering Socket#65370760::Socket(AddressFamily#23)
    System.Net.Sockets Verbose: 0 : [21440] Exiting Socket#65370760::Socket() 
    System.Net.Sockets Verbose: 0 : [21440] Entering Socket#65429669::Connect(196.38.158.118#1990076100)
    System.Net.Sockets Verbose: 0 : [21440] Entering Socket#65429669::Connect(196.38.158.118:7898#1990080542)
    System.Net.Sockets Information: 0 : [21440] Socket#65429669 - Created connection from 192.168.208.226:45419 to 196.38.158.118:7898.
    System.Net.Sockets Verbose: 0 : [21440] Exiting Socket#65429669::Connect() 
    System.Net.Sockets Verbose: 0 : [21440] Exiting Socket#65429669::Connect() 
    System.Net.Sockets Verbose: 0 : [21440] Entering Socket#65370760::Close()
    System.Net.Sockets Verbose: 0 : [21440] Entering Socket#65370760::Dispose()
    System.Net.Sockets Verbose: 0 : [21440] Exiting Socket#65370760::Close() 
    System.Net.Sockets Verbose: 0 : [21440] Exiting TcpClient#60800190::Connect() 
    System.Net.Sockets Verbose: 0 : [21440] Exiting TcpClient#60800190::TcpClient() 
    System.Net.Sockets Verbose: 0 : [21440] Entering Socket#65429669::Send()
    System.Net.Sockets Verbose: 0 : [21440] Data from Socket#65429669::Send
    System.Net.Sockets Verbose: 0 : [21440] 00000000 : 3C 72 65 71 75 65 73 74-3E 3C 45 76 65 6E 74 54 : <request><EventT
    System.Net.Sockets Verbose: 0 : [21440] 00000010 : 79 70 65 3E 41 75 74 68-65 6E 74 69 63 61 74 69 : ype>Authenticati
    System.Net.Sockets Verbose: 0 : [21440] 00000020 : 6F 6E 3C 2F 45 76 65 6E-74 54 79 70 65 3E 3C 65 : on</EventType><e
    System.Net.Sockets Verbose: 0 : [21440] 00000030 : 76 65 6E 74 3E 3C 55 73-65 72 50 69 6E 3E 30 31 : vent><UserPin>01
    System.Net.Sockets Verbose: 0 : [21440] 00000040 : 31 32 33 34 3C 2F 55 73-65 72 50 69 6E 3E 3C 44 : 1234</UserPin><D
    System.Net.Sockets Verbose: 0 : [21440] 00000050 : 65 76 69 63 65 49 64 3E-32 31 32 32 3C 2F 44 65 : eviceId>2122</De
    System.Net.Sockets Verbose: 0 : [21440] 00000060 : 76 69 63 65 49 64 3E 3C-44 65 76 69 63 65 53 65 : viceId><DeviceSe
    System.Net.Sockets Verbose: 0 : [21440] 00000070 : 72 3E 53 55 50 41 42 45-54 53 21 3C 2F 44 65 76 : r>BETS!</Dev
    System.Net.Sockets Verbose: 0 : [21440] 00000080 : 69 63 65 53 65 72 3E 3C-54 72 61 6E 73 54 79 70 : iceSer><TransTyp
    System.Net.Sockets Verbose: 0 : [21440] 00000090 : 65 3E 56 6F 75 63 68 65-72 3C 2F 54 72 61 6E 73 : e>Voucher</Trans
    System.Net.Sockets Verbose: 0 : [21440] 000000A0 : 54 79 70 65 3E 3C 2F 65-76 65 6E 74 3E 3C 2F 72 : Type></event></r
    System.Net.Sockets Verbose: 0 : [21440] 000000B0 : 65 71 75 65 73 74 3E                            : equest>
    System.Net.Sockets Verbose: 0 : [21440] Exiting Socket#65429669::Send() 	-> Int32#183
    System.Net.Sockets Verbose: 0 : [21440] Entering TcpClient#60800190::GetStream()
    System.Net.Sockets Verbose: 0 : [21440] Exiting TcpClient#60800190::GetStream() 	-> NetworkStream#62955487
    System.Net.Sockets Verbose: 0 : [21440] Entering Socket#65429669::Receive()
    

    kind regards

    Tony

    Wednesday, April 3, 2019 10:27 AM
  • User475983607 posted

    What kind of service are you connecting to?  An HTTP service or some other protocol?  Is the XML shown above from the telnet session or TcpClient?  

    Wednesday, April 3, 2019 11:13 AM
  • User767034699 posted

    Hi mgebhard,

    All data requests and responses are XML strings that are communicated via TCP/IP socket connection protocol. The xml response its shown on the telnet session.

    kind regards

    Tony

    Wednesday, April 3, 2019 11:35 AM
  • User475983607 posted

    tonyR6

    All data requests and responses are XML strings that are communicated via TCP/IP socket connection protocol. The xml response its shown on the telnet session.

    In my experience, when you send anything over a TCP Socket there is a protocol involved.  You can't simply send XML over a TCP connection and expect it to work.  Usually you have to send some other bits of data like the amount of bytes in the payload. Otherwise, the listener (server) has no idea when the input stream ends.  The listener will not be able to send a response if it does not know the input stream has ended.  

    You must have documentation that explains how to use this service?

    Wednesday, April 3, 2019 11:43 AM
  • User767034699 posted

    Hi there mgebhard,

    they dont have any examples of how to use the service. But when i asked, they said theres no service running. see below whats on the documentation.

    "The connection to an AEON switch from a 3rd party host is established via a preconfigured VPN or other
    predetermined secure connection. All connections are made via TCP/IP. The AEON switch is a powerful
    multithreaded server, so a host can open multiple simultaneous connections and perform transaction
    processing."

    kind regards

    Tony

    Wednesday, April 3, 2019 12:00 PM
  • User475983607 posted

    Hi there mgebhard,

    they dont have any examples of how to use the service. But when i asked, they said theres no service running. see below whats on the documentation.

    "The connection to an AEON switch from a 3rd party host is established via a preconfigured VPN or other
    predetermined secure connection. All connections are made via TCP/IP. The AEON switch is a powerful
    multithreaded server, so a host can open multiple simultaneous connections and perform transaction
    processing."

    kind regards

    Tony

    So this question has absolutely nothing to do with ASP.NET or communicating with a service.  You are trying to communicate with a hardware device.   I'm very confident, having a lot of experience with embedded devices, that there is a protocol you are missing.  You'll need to read the dev documentation that comes with the device.

    Wednesday, April 3, 2019 12:06 PM
  • User767034699 posted

    Hi mgebhard,

    thats the thing, it doesnt show any examples of connecting to the service. But i can see the example of the request xml that im supposed to send using ip address on specific port number.

    e.g of xml 

    <request>
     <EventType>Authentication</EventType>
     <event>
     <UserPin>xxxxx</UserPin>
     <DeviceId>xxx</DeviceId>
     <DeviceSer>xxx</DeviceSer>
     <TransType>AccountInfo</TransType>
     <Reference>xxxx</Reference>
     </event>
    </request>

    kind regards

    Tony

    Wednesday, April 3, 2019 12:55 PM
  • User475983607 posted

    tonyR6

    Hi mgebhard,

    thats the thing, it doesnt show any examples of connecting to the service. But i can see the example of the request xml that im supposed to send using ip address on specific port number.

    e.g of xml 

    <request>
     <EventType>Authentication</EventType>
     <event>
     <UserPin>xxxxx</UserPin>
     <DeviceId>xxx</DeviceId>
     <DeviceSer>xxx</DeviceSer>
     <TransType>AccountInfo</TransType>
     <Reference>xxxx</Reference>
     </event>
    </request>

    kind regards

    Tony

    I'm guessing you have a Z-Wave interface device that bridges your Ethernet network with the mess network.  You are trying to communicate with the Z-Wave hub.  I find it hard to believe that sending raw XML over TCP could possibly work. Usually the XML is within another protocol like HTTP.  The HTTP protocol tells the hub what type of encoding to expect as well as the length of the payload.  Where are you getting this information?  Do you have a link to the documentation?

    If telnet works as expected then the only other thing it could be the payload.  Since we cannot see that part of your code, there is not much we can do.  Try setting a break point and verifying the payload matches what you sent via telnet.

    Other than that, I believe you are in the wrong support forum and need to contact support for the device.

    Wednesday, April 3, 2019 1:30 PM
  • User767034699 posted

    Hi there mgebhard,

    thanks for the reply,

    i dont use any code to telnet. i use a normal cmd to telnet see below links to the telnet screen shorts

    https://imgur.com/uvNSW8e


    https://imgur.com/XqeMbPZ


    https://imgur.com/nkp9nXP

    kind regards

    Tony

    Wednesday, April 3, 2019 2:18 PM
  • User475983607 posted

    Hi there mgebhard,

    thanks for the reply,

    i dont use any code to telnet. i use a normal cmd to telnet see below links to the telnet screen shorts

    https://imgur.com/uvNSW8e


    https://imgur.com/XqeMbPZ


    https://imgur.com/nkp9nXP

    kind regards

    Tony

    I know how telnet works and understand you are running telnet from the command line.  You need to come to terms that you are trying to interface with 3rd party hardware using TCP and this is an ASP.NET support forum.   It is unlikely anyone on this forum will be able to reproduce this issue.

    Wednesday, April 3, 2019 2:33 PM
  • User767034699 posted

    Hi mgebhard,

    thanks for the response,

    I understand, looking at the details given. if im able to send the request and connect to the device, but unable to receive the response it means something is closing the connection or maybe the hardware is unable to stream back. Just that im new to this kind of integration.

    kind regards

    Tony

    Thursday, April 4, 2019 7:08 AM
  • User-893317190 posted

    Hi tonyR6 ,

    I have made a test using socket and tcpclient and both have a success.

    Below is my code.

     int port = 4600;
                string host = "127.0.0.1";
    
                IPAddress ip = IPAddress.Parse(host);
                IPEndPoint ipe = new IPEndPoint(ip, port);
    
    
                IPAddress ipclient = IPAddress.Parse("127.0.0.1");
                IPEndPoint ipc = new IPEndPoint(ip, 3725);
    
                Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                clientSocket.Bind(ipc);
                clientSocket.Connect(ipe);
    
                //send message
                string sendStr = "send to server : hello,ni hao";
                byte[] sendBytes = Encoding.ASCII.GetBytes(sendStr);
                clientSocket.Send(sendBytes);
              
                //receive message
                string recStr = "";
                byte[] recBytes = new byte[4096];
                int bytes = clientSocket.Receive(recBytes, recBytes.Length, 0);
                recStr += Encoding.ASCII.GetString(recBytes, 0, bytes);
                Response.Write(recStr);
    
                clientSocket.Close();

    Server side.

     TcpListener tcplistener = new TcpListener(IPAddress.Any, 4600);
                tcplistener.Start();
                TcpClient client = tcplistener.AcceptTcpClient();
                NetworkStream clientStream = client.GetStream();
    
                byte[] message = new byte[4096];
                int bytesRead = 0;
    
              
               // while (true)
               // {
                    bytesRead = 0;
    
                    try
                    {
                        //blocks until a client sends a message
                        bytesRead = clientStream.Read(message, 0, 4096);
                    }
                    catch
                    {
                        //a socket error has occured
                        Response.Write("Error:receive msg error");
                   
                    }
    
                 
    
                    //message has successfully been received
                    ASCIIEncoding encoder = new ASCIIEncoding();
                    //System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead));
                    string recvstr = encoder.GetString(message, 0, bytesRead);
                    Response.Write(String.Format("Recv:[{1}]:msg:@[{0}] @{2}<br/>", recvstr, client.Client.LocalEndPoint, DateTime.Now.ToString()));
    
                    //send msg to client
                    string sendstr = "Server OK";
                  
                    byte[] buffer = encoder.GetBytes(sendstr);
                    clientStream.Write(buffer, 0, buffer.Length);
                    clientStream.Flush();
                            Response.Write(String.Format("Sent:[{1}]:msg:@[{0}] @{2}\r\n", sendstr, client.Client.LocalEndPoint, DateTime.Now.ToString()));
               // }
    
                client.Close();
            }
    

    You could use the code to test whether you could receive message from localhost , and telnet's default port is 23, check whether your computer has opened other ports.

    If not , please open the port at which your .net client send message.

    https://windowsreport.com/open-firewall-ports/

    My result.

    Best regards,

    Ackerly Xu

    Thursday, April 4, 2019 8:32 AM
  • User767034699 posted

    thanks Ackerly for the reply,

    i was successful on local host using the code, on telnet im able to request and receive a response. when i do it via c# it doesnt even hit the server on the client machine but only when i telnet.

    kind regards

    Tony

    Thursday, April 4, 2019 12:44 PM
  • User-893317190 posted

    Hi tonyR6,

    If it works in your local host and doesn't work  when sending message to remote server , there may be something wrong with your network with your remote server.

    It may be caused by firewall , try to close it and have a try.

    https://www.lifewire.com/how-to-disable-the-windows-firewall-2624505

    Best regards,

    Ackerly Xu

    Monday, April 8, 2019 1:18 AM
  • User767034699 posted

    Hi Ackerly, 

    Windows firewall was already turned off, if i can telnet to their server but not able to connect on c# using tcpclient() function. Im thinking of using the below code.

       System.Diagnostics.ProcessStartInfo procStartInfo =
               new System.Diagnostics.ProcessStartInfo("cmd.exe");

    kind regards

    Tony

    Monday, April 8, 2019 11:46 AM
  • User-893317190 posted

    Hi tonyR6,

    After some search, I find telnet is different from tcp although it uses tcp.

    You could refer to the link below  to learn how to send a telnet request in c#.

    https://stackoverflow.com/questions/30614152/how-to-telnet-from-remote-server-c-sharp

    Best regards,

    Ackerly Xu

    Tuesday, April 9, 2019 1:31 AM
  • User767034699 posted

    Hi Ackerly,

    thanks for the response once again,

    i have visited the forum, however i dont need to login to telnet. but just send request and receive a response from it. i have tried this code on my side. But im able to telnet and connect to the remote client server, but not able to key in the request.

      System.Diagnostics.ProcessStartInfo procStartInfo =
               new System.Diagnostics.ProcessStartInfo("cmd.exe");
               procStartInfo.Arguments = "/k telnet 196.38.158.118 7898";
    
               procStartInfo.UseShellExecute = false;
             
               // Do not create the black window.
               procStartInfo.CreateNoWindow = false;
               // Now we create a process, assign its ProcessStartInfo and start it
               System.Diagnostics.Process proc = new System.Diagnostics.Process();
               proc.StartInfo = procStartInfo;
               proc.StartInfo.RedirectStandardInput = false;
               proc.StartInfo.RedirectStandardOutput = false;
    
    
          
               proc.Start();

    now i want to be able to key in the request and read out the response in a timely manner.

    kind regards

    Tony

    Tuesday, April 9, 2019 9:46 AM
  • User-893317190 posted

    Hi tonyR6,

    If you want to use cmd to send request , you could get the result through process. StandardOutput property.

    Below is a sample.

    using (Process p = new Process())
                {
                    p.StartInfo.CreateNoWindow = true;
                    p.StartInfo.RedirectStandardOutput = true;
                    p.StartInfo.UseShellExecute = false;
                    p.StartInfo.Arguments = "/c ping www.google.com";
                    p.StartInfo.FileName = @"C:\Windows\System32\cmd.exe";
                    p.Start();
    
                    string line;
                    string result="";
                    while ((line = p.StandardOutput.ReadLine()) != null)
                    {
                        result += line;
                    }
    
                    p.WaitForExit();
                    Response.Write(result);
                }

    Please refer to https://stackoverflow.com/questions/206323/how-to-execute-command-line-in-c-get-std-out-results

    Best regards,

    Ackerly Xu

    Wednesday, April 10, 2019 1:23 AM
  • User767034699 posted

    Hi Ackerly,

    thanks for the reply, how about using it with combination of vbscript.

    set WshShell = WScript.CreateObject("WScript.Shell")
    WshShell.run("telnet.exe 196.38.158.118 7898 -f c:\out.txt")
    WshShell.SendKeys("{Enter}")
    WScript.Sleep 500
    WshShell.SendKeys"<request><EventType>Authentication</EventType><event><UserPin>011234</UserPin><DeviceId>2122</DeviceId><DeviceSer>xxxx</DeviceSer><TransType>CellCBundles</TransType><Reference>TestAuthentication</Reference></event></request>"
    WshShell.SendKeys("{Enter}")

    kind regards

    Tony

    Thursday, April 18, 2019 2:13 PM