btcpayserver/BTCPayServer/Services/SocketFactory.cs

65 lines
1.8 KiB
C#
Raw Normal View History

using System;
2019-03-31 05:08:08 +02:00
using NBitcoin;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using BTCPayServer.Configuration;
using NBitcoin.Protocol.Connectors;
using NBitcoin.Protocol;
namespace BTCPayServer.Services
{
public class SocketFactory
{
private readonly BTCPayServerOptions _options;
public SocketFactory(BTCPayServerOptions options)
{
_options = options;
}
2019-03-31 06:16:05 +02:00
public async Task<Socket> ConnectAsync(EndPoint endPoint, CancellationToken cancellationToken)
{
DefaultEndpointConnector connector = new DefaultEndpointConnector();
NodeConnectionParameters connectionParameters = new NodeConnectionParameters();
if (_options.SocksEndpoint != null)
{
connectionParameters.TemplateBehaviors.Add(new NBitcoin.Protocol.Behaviors.SocksSettingsBehavior()
{
SocksEndpoint = _options.SocksEndpoint
});
}
var socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
try
{
await connector.ConnectSocket(socket, endPoint, connectionParameters, cancellationToken);
}
catch
{
SafeCloseSocket(socket);
}
return socket;
}
internal static void SafeCloseSocket(System.Net.Sockets.Socket socket)
{
try
{
socket.Shutdown(SocketShutdown.Both);
}
catch
{
}
try
{
socket.Dispose();
}
catch
{
}
}
}
}