#if !NETFX_CORE
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
namespace Plane.Communication
{
///
/// 提供作为 TCP 客户端通信的能力。
///
public class TcpConnection : TcpConnectionBase
{
private string _remoteHostname;
const int tcpReceiveBufferSize = 20 * 1024; //40 * 1024,
const int tcpReceiveTimeout = 1200;
private int _remotePort;
public TcpConnection(string remoteHostname, int remotePort = 5250)
{
_remoteHostname = remoteHostname;
_remotePort = remotePort;
_client = new TcpClient
{
ReceiveBufferSize = tcpReceiveBufferSize,
ReceiveTimeout = tcpReceiveTimeout
};
}
public void Open()
{
if (!IsOpen)
{
try
{
_client.Connect(_remoteHostname, _remotePort);
}
catch (SocketException)
{
CreateClientAndConnect();
}
catch (ObjectDisposedException)
{
CreateClientAndConnect();
}
_isBroken = false;
}
_stream = _client.GetStream();
}
public async Task BindIP(string ip)
{
bool bind = false;
try
{
IPAddress IPLocal = IPAddress.Parse(ip);
_client.Client.Bind(new IPEndPoint(IPLocal, 0));
bind = true;
}
catch
{
bind = false;
}
await Task.Delay(10).ConfigureAwait(false);
return bind;
}
public override async Task OpenAsync()
{
string logstr;
if (!IsOpen)
{
if (_client == null)
CreateClientAndConnect();
try
{
var connectTask = _client.ConnectAsync(_remoteHostname, _remotePort);
if (await Task.WhenAny(connectTask, Task.Delay(5000)) == connectTask)
{
await connectTask.ConfigureAwait(false);
}
else
{
// Connection timed out
throw new TimeoutException("Connection timed out");
}
}
catch (SocketException e)
{
logstr = e.Message;
}
catch (ObjectDisposedException)
{
}
_isBroken = false;
}
_stream = _client.GetStream();
}
private void CreateClientAndConnect()
{
_client = new TcpClient(_remoteHostname, _remotePort)
{
ReceiveBufferSize = tcpReceiveBufferSize,
ReceiveTimeout = tcpReceiveTimeout
};
}
private async Task CreateClientAndConnectAsync()
{
_client = new TcpClient
{
ReceiveBufferSize = tcpReceiveBufferSize,// 40 * 1024,
ReceiveTimeout = tcpReceiveTimeout// 1200
};
await _client.ConnectAsync(_remoteHostname, _remotePort).ConfigureAwait(false);
}
}
}
#endif