Unosquare
    Show / Hide Table of Contents

    Class Connection

    Represents a network connection either on the server or on the client. It wraps a TcpClient and its corresponding network streams. It is capable of working in 2 modes. Typically on the server side you will need to enable continuous reading and events. On the client side you may want to disable continuous reading and use the Read methods available. In continuous reading mode Read methods are not available and will throw an invalid operation exceptions if they are used. Continuous Reading Mode: Subscribe to data reception events, it runs a background thread, don't use Read methods Manual Reading Mode: Data reception events are NEVER fired. No background threads are used. Use Read methods to receive data.

    Inheritance
    Object
    Connection
    Implements
    IDisposable
    Inherited Members
    Object.ToString()
    Object.Equals(Object)
    Object.Equals(Object, Object)
    Object.ReferenceEquals(Object, Object)
    Object.GetHashCode()
    Object.GetType()
    Object.MemberwiseClone()
    Namespace: Swan.Net
    Syntax
    public sealed class Connection : IDisposable
    Examples

    The following code explains how to create a TCP server.

    using System.Text;
    using Swan.Net;
    
    class Example
    {
        static void Main()
        {
            // create a new connection listener on a specific port
            var connectionListener = new ConnectionListener(1337);
    
            // handle the OnConnectionAccepting event
            connectionListener.OnConnectionAccepted += async (s, e) =>
            {
                 // create a new connection 
                 using (var con = new Connection(e.Client))
                 {               
                    await con.WriteLineAsync("Hello world!");
                 }
            };
    
            connectionListener.Start();
            Console.ReadLine)=ñ
        }
    }

    The following code describes how to create a TCP client.

    using System.Net.Sockets;
    using System.Text;
    using System.Threading.Tasks;
    using Swan.Net;
    
    class Example
    {
        static async Task Main()
        {
            // create a new TcpClient object
            var client = new TcpClient();
    
            // connect to a specific address and port
            client.Connect("localhost", 1337);
    
            //create a new connection with specific encoding,
            //new line sequence and continuous reading disabled
            using (var cn = new Connection(client, Encoding.UTF8, "\r\n", true, 0))
            {               
               var response = await cn.ReadTextAsync();
            }
        }
    }

    Constructors

    Connection(TcpClient)

    Initializes a new instance of the Connection class in continuous reading mode. It uses UTF8 encoding, CRLF as a new line sequence and disables a protocol block size.

    Declaration
    public Connection(TcpClient client)
    Parameters
    Type Name Description
    TcpClient client

    The client.

    Connection(TcpClient, Int32)

    Initializes a new instance of the Connection class in continuous reading mode. It uses UTF8 encoding, disables line sequences, and uses a protocol block size instead.

    Declaration
    public Connection(TcpClient client, int blockSize)
    Parameters
    Type Name Description
    TcpClient client

    The client.

    Int32 blockSize

    Size of the block.

    Connection(TcpClient, Encoding, String, Boolean, Int32)

    Initializes a new instance of the Connection class.

    Declaration
    public Connection(TcpClient client, Encoding textEncoding, string newLineSequence, bool disableContinuousReading, int blockSize)
    Parameters
    Type Name Description
    TcpClient client

    The client.

    Encoding textEncoding

    The text encoding.

    String newLineSequence

    The new line sequence used for read and write operations.

    Boolean disableContinuousReading

    if set to true [disable continuous reading].

    Int32 blockSize

    Size of the block. -- set to 0 or less to disable.

    Properties

    ActiveStream

    Gets the active stream. Returns an SSL stream if the connection is secure, otherwise returns the underlying NetworkStream.

    Declaration
    public Stream ActiveStream { get; }
    Property Value
    Type Description
    Stream

    The active stream.

    ConnectionDuration

    Gets the duration of the connection.

    Declaration
    public TimeSpan ConnectionDuration { get; }
    Property Value
    Type Description
    TimeSpan

    The duration of the connection.

    ConnectionStartTime

    Gets the start time at which the connection was started in local time.

    Declaration
    public DateTime ConnectionStartTime { get; }
    Property Value
    Type Description
    DateTime

    The connection start time.

    ConnectionStartTimeUtc

    Gets the start time at which the connection was started in UTC.

    Declaration
    public DateTime ConnectionStartTimeUtc { get; }
    Property Value
    Type Description
    DateTime

    The connection start time UTC.

    DataReceivedIdleDuration

    Gets how long has elapsed since data was last received.

    Declaration
    public TimeSpan DataReceivedIdleDuration { get; }
    Property Value
    Type Description
    TimeSpan

    DataReceivedLastTimeUtc

    Gets the last time data was received at in UTC.

    Declaration
    public DateTime DataReceivedLastTimeUtc { get; }
    Property Value
    Type Description
    DateTime

    The data received last time UTC.

    DataSentIdleDuration

    Gets how long has elapsed since data was last sent.

    Declaration
    public TimeSpan DataSentIdleDuration { get; }
    Property Value
    Type Description
    TimeSpan

    The duration of the data sent idle.

    DataSentLastTimeUtc

    Gets the last time at which data was sent in UTC.

    Declaration
    public DateTime DataSentLastTimeUtc { get; }
    Property Value
    Type Description
    DateTime

    The data sent last time UTC.

    Id

    Gets the unique identifier of this connection. This field is filled out upon instantiation of this class.

    Declaration
    public Guid Id { get; }
    Property Value
    Type Description
    Guid

    The identifier.

    IsActiveStreamSecure

    Gets a value indicating whether the current connection stream is an SSL stream.

    Declaration
    public bool IsActiveStreamSecure { get; }
    Property Value
    Type Description
    Boolean

    true if this instance is active stream secure; otherwise, false.

    IsConnected

    Gets a value indicating whether this connection is connected. Remarks: This property polls the socket internally and checks if it is available to read data from it. If disconnect has been called, then this property will return false.

    Declaration
    public bool IsConnected { get; }
    Property Value
    Type Description
    Boolean

    true if this instance is connected; otherwise, false.

    IsContinuousReadingEnabled

    Gets a value indicating whether this connection is in continuous reading mode. Remark: Whenever a disconnect event occurs, the background thread is terminated and this property will return false whenever the reading thread is not active. Therefore, even if continuous reading was not disabled in the constructor, this property might return false.

    Declaration
    public bool IsContinuousReadingEnabled { get; }
    Property Value
    Type Description
    Boolean

    true if this instance is continuous reading enabled; otherwise, false.

    LocalEndPoint

    Gets the local end point of this TCP connection.

    Declaration
    public IPEndPoint LocalEndPoint { get; }
    Property Value
    Type Description
    IPEndPoint

    The local end point.

    ProtocolBlockSize

    When in continuous reading mode, and if set to greater than 0, a Data reception event will be fired whenever the amount of bytes determined by this property has been received. Useful for fixed-length message protocols.

    Declaration
    public int ProtocolBlockSize { get; }
    Property Value
    Type Description
    Int32

    The size of the protocol block.

    RemoteClient

    Gets the remote client of this TCP connection.

    Declaration
    public TcpClient? RemoteClient { get; }
    Property Value
    Type Description
    Nullable<TcpClient>

    The remote client.

    RemoteEndPoint

    Gets the remote end point of this TCP connection.

    Declaration
    public IPEndPoint RemoteEndPoint { get; }
    Property Value
    Type Description
    IPEndPoint

    The remote end point.

    TextEncoding

    Gets the text encoding for send and receive operations.

    Declaration
    public Encoding TextEncoding { get; }
    Property Value
    Type Description
    Encoding

    The text encoding.

    Methods

    Disconnect()

    Disconnects this connection.

    Declaration
    public void Disconnect()

    Dispose()

    Declaration
    public void Dispose()

    ReadDataAsync(CancellationToken)

    Reads data asynchronously from the remote stream with a 5000 millisecond timeout.

    Declaration
    public Task<byte[]> ReadDataAsync(CancellationToken cancellationToken = default(CancellationToken))
    Parameters
    Type Name Description
    CancellationToken cancellationToken

    The cancellation token.

    Returns
    Type Description
    Task<Byte[]>

    A byte array containing the results the specified sequence of bytes.

    ReadDataAsync(TimeSpan, CancellationToken)

    Reads data from the remote client asynchronously and with the given timeout.

    Declaration
    public Task<byte[]> ReadDataAsync(TimeSpan timeout, CancellationToken cancellationToken = default(CancellationToken))
    Parameters
    Type Name Description
    TimeSpan timeout

    The timeout.

    CancellationToken cancellationToken

    The cancellation token.

    Returns
    Type Description
    Task<Byte[]>

    A byte array containing the results of encoding the specified set of characters.

    Exceptions
    Type Condition
    InvalidOperationException

    Read methods have been disabled because continuous reading is enabled.

    TimeoutException

    Reading data from {ActiveStream} timed out in {timeout.TotalMilliseconds} m.

    ReadLineAsync(CancellationToken)

    Performs the same task as this method's overload but it defaults to a read timeout of 30 seconds.

    Declaration
    public Task<string> ReadLineAsync(CancellationToken cancellationToken = default(CancellationToken))
    Parameters
    Type Name Description
    CancellationToken cancellationToken

    The cancellation token.

    Returns
    Type Description
    Task<String>

    A task that represents the asynchronous read operation. The value of the TResult parameter contains the next line from the stream, or is null if all the characters have been read.

    ReadLineAsync(TimeSpan, CancellationToken)

    Reads the next available line of text in queue. Return null when no text is read. This method differs from the rest of the read methods because it keeps an internal queue of lines that are read from the stream and only returns the one line next in the queue. It is only recommended to use this method when you are working with text-based protocols and the rest of the read methods are not called.

    Declaration
    public Task<string> ReadLineAsync(TimeSpan timeout, CancellationToken cancellationToken = default(CancellationToken))
    Parameters
    Type Name Description
    TimeSpan timeout

    The timeout.

    CancellationToken cancellationToken

    The cancellation token.

    Returns
    Type Description
    Task<String>

    A task with a string line from the queue.

    Exceptions
    Type Condition
    InvalidOperationException

    Read methods have been disabled because continuous reading is enabled.

    ReadTextAsync(CancellationToken)

    Asynchronously reads data as text with a 5000 millisecond timeout.

    Declaration
    public Task<string> ReadTextAsync(CancellationToken cancellationToken = default(CancellationToken))
    Parameters
    Type Name Description
    CancellationToken cancellationToken

    The cancellation token.

    Returns
    Type Description
    Task<String>

    When this method completes successfully, it returns the contents of the file as a text string.

    ReadTextAsync(TimeSpan, CancellationToken)

    Asynchronously reads data as text with the given timeout.

    Declaration
    public Task<string> ReadTextAsync(TimeSpan timeout, CancellationToken cancellationToken = default(CancellationToken))
    Parameters
    Type Name Description
    TimeSpan timeout

    The timeout.

    CancellationToken cancellationToken

    The cancellation token.

    Returns
    Type Description
    Task<String>

    A String that contains the results of decoding the specified sequence of bytes.

    UpgradeToSecureAsClientAsync(String, Nullable<RemoteCertificateValidationCallback>)

    Upgrades the active stream to an SSL stream if this connection object is hosted in the client.

    Declaration
    public Task<bool> UpgradeToSecureAsClientAsync(string hostname = null, RemoteCertificateValidationCallback? callback = default(RemoteCertificateValidationCallback? ))
    Parameters
    Type Name Description
    String hostname

    The hostname.

    Nullable<RemoteCertificateValidationCallback> callback

    The callback.

    Returns
    Type Description
    Task<Boolean>

    A tasks with true if the upgrade to SSL was successful; otherwise, false.

    UpgradeToSecureAsServerAsync(X509Certificate2)

    Upgrades the active stream to an SSL stream if this connection object is hosted in the server.

    Declaration
    public Task<bool> UpgradeToSecureAsServerAsync(X509Certificate2 serverCertificate)
    Parameters
    Type Name Description
    X509Certificate2 serverCertificate

    The server certificate.

    Returns
    Type Description
    Task<Boolean>

    true if the object is hosted in the server; otherwise, false.

    WriteDataAsync(Byte[], Boolean, CancellationToken)

    Writes data asynchronously.

    Declaration
    public Task WriteDataAsync(byte[] buffer, bool forceFlush, CancellationToken cancellationToken = default(CancellationToken))
    Parameters
    Type Name Description
    Byte[] buffer

    The buffer.

    Boolean forceFlush

    if set to true [force flush].

    CancellationToken cancellationToken

    The cancellation token.

    Returns
    Type Description
    Task

    A task that represents the asynchronous write operation.

    WriteLineAsync(String, Encoding, CancellationToken)

    Writes a line of text asynchronously. The new line sequence is added automatically at the end of the line.

    Declaration
    public Task WriteLineAsync(string line, Encoding encoding, CancellationToken cancellationToken = default(CancellationToken))
    Parameters
    Type Name Description
    String line

    The line.

    Encoding encoding

    The encoding.

    CancellationToken cancellationToken

    The cancellation token.

    Returns
    Type Description
    Task

    A task that represents the asynchronous write operation.

    WriteLineAsync(String, CancellationToken)

    Writes a line of text asynchronously. The new line sequence is added automatically at the end of the line.

    Declaration
    public Task WriteLineAsync(string line, CancellationToken cancellationToken = default(CancellationToken))
    Parameters
    Type Name Description
    String line

    The line.

    CancellationToken cancellationToken

    The cancellation token.

    Returns
    Type Description
    Task

    A task that represents the asynchronous write operation.

    WriteTextAsync(String, Encoding, CancellationToken)

    Writes text asynchronously.

    Declaration
    public Task WriteTextAsync(string text, Encoding encoding, CancellationToken cancellationToken = default(CancellationToken))
    Parameters
    Type Name Description
    String text

    The text.

    Encoding encoding

    The encoding.

    CancellationToken cancellationToken

    The cancellation token.

    Returns
    Type Description
    Task

    A task that represents the asynchronous write operation.

    WriteTextAsync(String, CancellationToken)

    Writes text asynchronously.

    Declaration
    public Task WriteTextAsync(string text, CancellationToken cancellationToken = default(CancellationToken))
    Parameters
    Type Name Description
    String text

    The text.

    CancellationToken cancellationToken

    The cancellation token.

    Returns
    Type Description
    Task

    A task that represents the asynchronous write operation.

    Events

    ClientDisconnected

    Occurs when a client is disconnected

    Declaration
    public event EventHandler ClientDisconnected
    Event Type
    Type Description
    EventHandler

    ConnectionFailure

    Occurs when an error occurs while upgrading, sending, or receiving data in this client

    Declaration
    public event EventHandler<ConnectionFailureEventArgs> ConnectionFailure
    Event Type
    Type Description
    EventHandler<ConnectionFailureEventArgs>

    DataReceived

    Occurs when the receive buffer has encounters a new line sequence, the buffer is flushed or the buffer is full.

    Declaration
    public event EventHandler<ConnectionDataReceivedEventArgs> DataReceived
    Event Type
    Type Description
    EventHandler<ConnectionDataReceivedEventArgs>

    Implements

    System.IDisposable

    See Also

    IDisposable

    Comments

    Back to top Copyright © 2017-2019 Unosquare