我目前正在将硬件库移植到.NET Core。通信在TCP上工作。我在使用' Socket.BeginReceive'方法。 MSDN
似乎.NET Core中没有等效的方法。如何从TCP套接字接收数据?
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();
}
}
答案 0 :(得分:2)
我找到了另一种方法。希望这有助于其他人。
基本上我刚刚使用NetworkStream
类。您可以通过调用TcpClient.GetStream()
来获取实例。如果您使用using
阻止GetStream
,则using
之后您的连接将被关闭。这就是我在我的例子中没有使用它的原因,因为我需要连接才能保持活力。
我的示例代码:
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;
}