TCP Listener Reading date from client but after some time it stuck

40 views Asked by At

I am working on TCP Listener in C# application where we are sending <ACK> to instrument and then instrument is sending the response to us. In my case what is happening like I can able to get first response and then after complete response received then it's stuck on. So problem is when instrument is sending second response then it is not able to get that response. I need to close the application and then application will send <ACK> and then get response.... like that its working but i want this to be execute continously and able to capture response from instrument.

This is my code:

private void button1_Click(object sender, EventArgs e)
{
    textBox1.Text = "";
    data = "";
                 
    IPAddress ipAddress = IPAddress.Parse(txtIpAddress.Text); 
    int port = Convert.ToInt32(txtPort.Text);

    // Create a TCP listener
    TcpListener tcpListener = new TcpListener(ipAddress, port);

    try
    {
        // Start listening for incoming connections
        tcpListener.Start();
        MessageBox.Show("Waiting for a connection...");

        TcpClient client = tcpListener.AcceptTcpClient();

        while (true)
        {
            // Accept the client connection

            // Handle the client in a separate thread or function
            HandleClient(client);
        }
    
        MessageBox.Show(data);
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error: " + ex.Message);
    }
    finally
    {
        // Stop listening when done
        tcpListener.Stop();
        MessageBox.Show("Listener stopped.");
    }
}

void HandleClient(TcpClient client)
{
    // Get the network stream for reading and writing data
    NetworkStream stream = client.GetStream();
           
    byte[] ackData = { 6 };
    stream.Write(ackData, 0, ackData.Length);
           
    // Receive the HL7 string from the machine
    byte[] hl7Buffer = new byte[1024]; // Adjust the buffer size as needed
    int bytesRead = stream.Read(hl7Buffer, 0, hl7Buffer.Length);  // Here it gets stuck after some time 
            
    string hl7Response = Encoding.UTF8.GetString(hl7Buffer, 0, bytesRead);
          
    if (data == "")
    {
        data = hl7response;
    }
    else
    {
        data = data +hl7response;
    }

    // Close the connection
    // stream.Close();
    // client.Close();
}
0

There are 0 answers