Mat*_*Mat 2 c# sockets tcp tcpclient .net-core
我目前正在将硬件库移植到 .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();
}
}
Run Code Online (Sandbox Code Playgroud)
我找到了另一种方法来做到这一点。希望这对其他人有帮助。
基本上我只是最终使用了这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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15069 次 |
| 最近记录: |