Search code examples
c#web-servicesasynchronoustcp

How to handle some asynchronous TcpClient responses?


I use this class for asynchronous client-server TCP network connection in my project.

I most connect to "Remote server" and send and receive data over TCP connection (from another company that we can't change communication method except TCP) in a "Interface Web Service".

This "Interface Web Service" handle "Client Apps" requests, create data and pass to "Remote server" over TCP connection, and pass (response) parsed response of "Remote server" to "Client Apps".

Note that current TCP connection, receive "Remote server" responses with OnDataReceived event. (This event is good and I want to use this event for next steps).

How can access and handle these asynchronous responses and pass complete response for "Client Apps" requests?

For summarize:

  1. Client app send request to Interface service
  2. Interface service create command for Remote server
  3. Remote server response to command from Interface service
  4. Now in Interface service, response handled with OnDataReceived EVENT, that I can not access it from Interface service that handle Client App request. Problem is here...

Look at this image to understand my scenario:

Scenario of communications


Solution

  • Thank you for reading and try to help me.

    I solve this problem by edit "NetConnection.cs" class and add this method:

    public Task<byte[]> SendAndReceiveData(byte[] data, int timeout = 10000)
    {
        CheckServerUsedAsClient();
        client.GetStream().Write(data, 0, data.Length);
    
        Task<byte[]> tskReceive = ReceiveFromAsync(this, timeout, true);
        tskReceive.Wait();
    
        return tskReceive;
    }
    

    and using this method to send request and receive data from "Remote server" like this:

    byte[] requestData = createByteArrayCommand();
    Task<byte[]> testTask = netConnectionObj.SendAndReceiveData(requestData);
    testTask.Wait();
    
    // testTask.Result <= contains server response