Plane.Sdk3/PlaneGcsSdk_Shared/Communication/TcpConnection.cs
zxd 4ffa68c99a 上传通信模块
修改了多网卡同时使用时的连接判断
2018-09-05 11:24:03 +08:00

115 lines
3.1 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#if !NETFX_CORE
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
namespace Plane.Communication
{
/// <summary>
/// 提供作为 TCP 客户端通信的能力。
/// </summary>
public class TcpConnection : TcpConnectionBase
{
private string _remoteHostname;
private int _remotePort;
public TcpConnection(string remoteHostname, int remotePort = 5250)
{
_remoteHostname = remoteHostname;
_remotePort = remotePort;
_client = new TcpClient
{
ReceiveBufferSize = 40 * 1024,
ReceiveTimeout = 1200
};
}
public void Open()
{
if (!IsOpen)
{
try
{
_client.Connect(_remoteHostname, _remotePort);
}
catch (SocketException)
{
CreateClientAndConnect();
}
catch (ObjectDisposedException)
{
CreateClientAndConnect();
}
_isBroken = false;
}
_stream = _client.GetStream();
}
public async Task<bool> 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()
{
if (!IsOpen)
{
try
{
await _client.ConnectAsync(_remoteHostname, _remotePort).ConfigureAwait(false);
}
//屏蔽掉异常处理
//CreateClientAndConnectAsync会new一个TcpClient并且重新连接
//之前设置的TcpClient中Socket Bind会无效在多网卡工作时会导致断线重连的时间特别长
catch (SocketException)
{
//await CreateClientAndConnectAsync();
}
catch (ObjectDisposedException)
{
//await CreateClientAndConnectAsync();
}
_isBroken = false;
}
_stream = _client.GetStream();
}
private void CreateClientAndConnect()
{
_client = new TcpClient(_remoteHostname, _remotePort)
{
ReceiveBufferSize = 40 * 1024,
ReceiveTimeout = 1200
};
}
private async Task CreateClientAndConnectAsync()
{
_client = new TcpClient
{
ReceiveBufferSize = 40 * 1024,
ReceiveTimeout = 1200
};
await _client.ConnectAsync(_remoteHostname, _remotePort).ConfigureAwait(false);
}
}
}
#endif