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();
}
}
I found another way to do it. Hope this helps someone else.
Basically I just ended up using the
NetworkStreamclass. You can get an instance by callingTcpClient.GetStream(). If you use ausingblock withGetStreamyour connection will get closed after theusing. 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: