Plane.Sdk3/PlaneGcsSdk_Shared/Communication/TcpConnectionBase.cs
zxd 72a9e28ed1 主要修改取消UDPserver 更换通信模块的通信
最小距离的修改
无悬停的快速航点模拟
时间长度的限定 如flyto的时间限定为4095
计划路线的修改:只显示当前航点的路线
飞控版本检测
航点失败续写和航点单写
2018-08-23 22:37:52 +08:00

159 lines
3.8 KiB
C#

#if !NETFX_CORE
using System;
using System.IO;
using System.Net.Sockets;
using System.Threading.Tasks;
namespace Plane.Communication
{
/// <summary>
/// 提供 TCP 通信的部分实现。
/// </summary>
public abstract class TcpConnectionBase : ExceptionThrownEventSource, IConnection
{
protected TcpClient _client;
protected bool _isBroken;
protected Stream _stream;
public int Available
{
get
{
try
{
if (_client.Connected)
return _client.Available;
else
return 0;
}
catch (ObjectDisposedException ex)
{
RaiseExceptionThrown(ex);
return 0;
}
}
}
public bool IsOnline
{
get
{
try
{
return !((_client.Client.Poll(1000, SelectMode.SelectRead) && (_client.Client.Available == 0)) || !_client.Client.Connected);
}
catch (ObjectDisposedException)
{
return false;
}
}
}
public bool IsOpen
{
get
{
try
{
return !_isBroken && _client.Connected;
}
catch (ObjectDisposedException)
{
return false;
}
}
}
public void Close()
{
_stream?.Close();
_client?.Close();
}
public abstract Task OpenAsync();
public int BytesToRead()
{
return 0;
}
public int Read(byte[] buffer, int offset, int count)
{
try
{
return _stream.Read(buffer, offset, count);
}
catch (ArgumentOutOfRangeException ex)
{
RaiseExceptionThrown(ex);
return 0;
}
catch (Exception ex) // 常见的是 IOException。
{
_isBroken = true;
RaiseExceptionThrown(ex);
return 0;
}
}
public async Task<int> ReadAsync(byte[] buffer, int offset, int count)
{
try
{
while (Available < count)
{
//if (!IsOpen)
// return 0;
if (!IsOnline)
return 0;
await Task.Delay(5).ConfigureAwait(false);
}
return await _stream.ReadAsync(buffer, offset, count);
}
catch (Exception ex)
{
_isBroken = true;
RaiseExceptionThrown(ex);
return 0;
}
}
public void Write(byte[] buffer, int offset, int count)
{
try
{
_stream.Write(buffer, offset, count);
}
catch (ArgumentOutOfRangeException ex)
{
RaiseExceptionThrown(ex);
}
catch (Exception ex)
{
_isBroken = true;
RaiseExceptionThrown(ex);
}
}
public async Task WriteAsync(byte[] buffer, int offset, int count)
{
try
{
await _stream.WriteAsync(buffer, offset, count);
}
catch (Exception ex)
{
_isBroken = true;
RaiseExceptionThrown(ex);
}
}
}
}
#endif