Mat
Mat

Reputation: 2072

how to receive data from a Socket in .NET Core?

I'm currently porting a hardware library to .NET Core. The communication works over TCP. I have problems with the 'Socket.BeginReceive' method. MSDN

It seems there is no equivalent method in .NET Core. How can I receive data from a TCP Socket?

private void InternalDataReceived(IAsyncResult ar)

{
    int dataCount = 0;
    byte[] buffer;

    try
    {
        if (_client != null && _client.Client != null)
        {
            dataCount = _client.Client.EndReceive(ar);
        }

        if (dataCount > 0)
        {
            try
            {
                buffer = new byte[dataCount];
                Array.Copy(_inBuffer, buffer, dataCount);

                if (DataReceived != null)
                {
                    DataReceived(buffer);
                }
            }
            catch (Exception exc)
            {
                if (exc is System.Net.Sockets.SocketException)
                {
                    Disconnect();
                    return;
                }
            }
            _client.Client.BeginReceive(_inBuffer, 0, _inBuffer.Length, SocketFlags.None, InternalDataReceived, null);
        }
    }
    catch
    {
        Disconnect();
    }
}

Upvotes: 2

Views: 17635

Answers (1)

Mat
Mat

Reputation: 2072

I found another way to do it. Hope this helps someone else.

Basically I just ended up using the NetworkStream class. You can get an instance by calling TcpClient.GetStream(). If you use a using block with GetStream your connection will get closed after the using. This is why I'm not using it in my example because I need the connection to stay alive.

MSDN NetworkStream.Read

My example code:

static void Main(string[] args)
{
    TcpClient client = new TcpClient();

    client.Client.Connect(IPAddress.Parse("192.168.100.5"), 8000);

    //Task.Run(() => ReadData(client));

    Task.Run(() => ReadDataLoop(client));

    client.Client.Send(Encoding.ASCII.GetBytes("{\"TID\":1111,\"blabla\":{}}"));


    while (true)
    {

    }
}

private static void ReadDataLoop(TcpClient client)
{
    while (true)
    {
        if (!client.Connected)
            break;

        string xxx = "";
        xxx = ReadData(client);
        Console.WriteLine(xxx);
    }
}

private static string ReadData(TcpClient client)
{
    string retVal;
    byte[] data = new byte[1024];

    NetworkStream stream = client.GetStream();


    byte[] myReadBuffer = new byte[1024];
    StringBuilder myCompleteMessage = new StringBuilder();
    int numberOfBytesRead = 0;


    do
    {
        numberOfBytesRead = stream.Read(myReadBuffer, 0, myReadBuffer.Length);

        myCompleteMessage.AppendFormat("{0}", Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead));

    }
    while (stream.DataAvailable);



    retVal = myCompleteMessage.ToString();


    return retVal;
}

Upvotes: 7

Related Questions