C# Sockets wait and listen

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • aatif
    New Member
    • Mar 2009
    • 28

    C# Sockets wait and listen

    I am working a c# socket based client application, the problem I am facing is I cannot get the reply of my message from the remote machine. The 'read' function returns (immediately) unsuccessful (0) most of the times. How can I wait for some response? Assume that the server needs some time (about 1 minute) for processing my request, before replying.

    Code:
    try
    {
        TcpClient tcpclnt = new TcpClient();
        Console.WriteLine("Connecting.....");
        tcpclnt.Connect(m_host, m_port); // ip and port of server
        Console.WriteLine("Connected");
        Console.Write("Enter the string to be transmitted : ");
        String str = Console.ReadLine();
        Stream stm = tcpclnt.GetStream();
        ASCIIEncoding asen = new ASCIIEncoding();
        byte[] ba = asen.GetBytes(str);
        Console.WriteLine("Transmitting.....");
        stm.Write(ba, 0, ba.Length);
                    
        byte[] bb = new byte[100];
        int k = 0, counter = 0;
    
        k = stm.Read(bb, 0, 100);
                    
        Console.Write("Response from "+m_host+": ");
        for (int i = 0; i < k; i++)
            Console.Write(Convert.ToChar(bb[i]));
    
        //Console.ReadKey(true);
        tcpclnt.Close();
        result = 1;
    }
  • Plater
    Recognized Expert Expert
    • Apr 2007
    • 7872

    #2
    You could consider waiting for tp.Available > 0.
    But you would need to remember to allow other processes/threads be active during it, and maybe make a timeout

    Comment

    Working...