1 // Licensed to the Apache Software Foundation(ASF) under one
2 // or more contributor license agreements.See the NOTICE file
3 // distributed with this work for additional information
4 // regarding copyright ownership.The ASF licenses this file
5 // to you under the Apache License, Version 2.0 (the
6 // "License"); you may not use this file except in compliance
7 // with the License. You may obtain a copy of the License at
9 // http://www.apache.org/licenses/LICENSE-2.0
11 // Unless required by applicable law or agreed to in writing,
12 // software distributed under the License is distributed on an
13 // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14 // KIND, either express or implied. See the License for the
15 // specific language governing permissions and limitations
20 using System.Net.Sockets;
21 using System.Threading;
22 using System.Threading.Tasks;
24 namespace Thrift.Transports.Client
26 // ReSharper disable once InconsistentNaming
27 public class TSocketClientTransport : TStreamClientTransport
29 private bool _isDisposed;
31 public TSocketClientTransport(TcpClient client)
33 TcpClient = client ?? throw new ArgumentNullException(nameof(client));
37 InputStream = client.GetStream();
38 OutputStream = client.GetStream();
42 public TSocketClientTransport(IPAddress host, int port)
47 public TSocketClientTransport(IPAddress host, int port, int timeout)
52 TcpClient = new TcpClient();
53 TcpClient.ReceiveTimeout = TcpClient.SendTimeout = timeout;
54 TcpClient.Client.NoDelay = true;
57 public TcpClient TcpClient { get; private set; }
58 public IPAddress Host { get; }
59 public int Port { get; }
65 if (TcpClient != null)
67 TcpClient.ReceiveTimeout = TcpClient.SendTimeout = value;
72 public override bool IsOpen
76 if (TcpClient == null)
81 return TcpClient.Connected;
85 public override async Task OpenAsync(CancellationToken cancellationToken)
87 if (cancellationToken.IsCancellationRequested)
89 await Task.FromCanceled(cancellationToken);
94 throw new TTransportException(TTransportException.ExceptionType.AlreadyOpen, "Socket already connected");
99 throw new TTransportException(TTransportException.ExceptionType.NotOpen, "Cannot open without port");
102 if (TcpClient == null)
104 throw new InvalidOperationException("Invalid or not initialized tcp client");
107 await TcpClient.ConnectAsync(Host, Port);
109 InputStream = TcpClient.GetStream();
110 OutputStream = TcpClient.GetStream();
113 public override void Close()
117 if (TcpClient != null)
125 protected override void Dispose(bool disposing)
131 TcpClient?.Dispose();
133 base.Dispose(disposing);