Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7075283
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T06:09:31+00:00 2026-05-28T06:09:31+00:00

I found this class on the internet but it didn’t have any example usage.

  • 0

I found this class on the internet but it didn’t have any example usage. I tried reading it and the <events> are confusing me. When I try to initialize an event it stays null even after the irc.DataRead+=new EventHandler<DataReadEventArgs>(irc_DataRead);

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace asynchronous
{

    /// <summary>
    /// Represents an asynchronous Tcp Client.
    /// </summary>
    public class Client
    {
        /// <summary>
        /// The default length for the read buffer.
        /// </summary>
        private const int DefaultClientReadBufferLength = 4096;

        /// <summary>
        /// The tcp client used for the outgoing connection.
        /// </summary>
        private readonly TcpClient client;

        /// <summary>
        /// The port to connect to on the remote server.
        /// </summary>
        private readonly int port;

        /// <summary>
        /// A reset event for use if a DNS lookup is required.
        /// </summary>
        private readonly ManualResetEvent dnsGetHostAddressesResetEvent = null;

        /// <summary>
        /// The length of the read buffer.
        /// </summary>
        private readonly int clientReadBufferLength;

        /// <summary>
        /// The addresses to try connection to.
        /// </summary>
        private IPAddress[] addresses;

        /// <summary>
        /// How many times to retry connection.
        /// </summary>
        private int retries;

        /// <summary>
        /// Occurs when the client connects to the server.
        /// </summary>
        public event EventHandler Connected;

        /// <summary>
        /// Occurs when the client disconnects from the server.
        /// </summary>
        public event EventHandler Disconnected;

        /// <summary>
        /// Occurs when data is read by the client.
        /// </summary>
        public event EventHandler<DataReadEventArgs> DataRead;

        /// <summary>
        /// Occurs when data is written by the client.
        /// </summary>
        public event EventHandler<DataWrittenEventArgs> DataWritten;

        /// <summary>
        /// Occurs when an exception is thrown during connection.
        /// </summary>
        public event EventHandler<ExceptionEventArgs> ClientConnectException;

        /// <summary>
        /// Occurs when an exception is thrown while reading data.
        /// </summary>
        public event EventHandler<ExceptionEventArgs> ClientReadException;

        /// <summary>
        /// Occurs when an exception is thrown while writing data.
        /// </summary>
        public event EventHandler<ExceptionEventArgs> ClientWriteException;

        /// <summary>
        /// Occurs when an exception is thrown while performing the DNS lookup.
        /// </summary>
        public event EventHandler<ExceptionEventArgs> DnsGetHostAddressesException;

        /// <summary>
        /// Constructor for a new client object based on a host name or server address string and a port.
        /// </summary>
        /// <param name="hostNameOrAddress">The host name or address of the server as a string.</param>
        /// <param name="port">The port on the server to connect to.</param>
        /// <param name="clientReadBufferLength">The clients read buffer length.</param>
        public Client(string hostNameOrAddress, int port, int clientReadBufferLength = DefaultClientReadBufferLength)
            : this(port, clientReadBufferLength)
        {
            this.dnsGetHostAddressesResetEvent = new ManualResetEvent(false);
            Dns.BeginGetHostAddresses(hostNameOrAddress, this.DnsGetHostAddressesCallback, null);
        }

        /// <summary>
        /// Constructor for a new client object based on a number of IP Addresses and a port.
        /// </summary>
        /// <param name="addresses">The IP Addresses to try connecting to.</param>
        /// <param name="port">The port on the server to connect to.</param>
        /// <param name="clientReadBufferLength">The clients read buffer length.</param>
        public Client(IPAddress[] addresses, int port, int clientReadBufferLength = DefaultClientReadBufferLength)
            : this(port, clientReadBufferLength)
        {
            this.addresses = addresses;
        }

        /// <summary>
        /// Constructor for a new client object based on a single IP Address and a port.
        /// </summary>
        /// <param name="address">The IP Address to try connecting to.</param>
        /// <param name="port">The port on the server to connect to.</param>
        /// <param name="clientReadBufferLength">The clients read buffer length.</param>
        public Client(IPAddress address, int port, int clientReadBufferLength = DefaultClientReadBufferLength)
            : this(new[] { address }, port, clientReadBufferLength)
        {
        }

        /// <summary>
        /// Private constructor for a new client object.
        /// </summary>
        /// <param name="port">The port on the server to connect to.</param>
        /// <param name="clientReadBufferLength">The clients read buffer length.</param>
        private Client(int port, int clientReadBufferLength)
        {
            this.client = new TcpClient();
            this.port = port;
            this.clientReadBufferLength = clientReadBufferLength;
        }

        /// <summary>
        /// Starts an asynchronous connection to the remote server.
        /// </summary>
        public void Connect()
        {
            if (this.dnsGetHostAddressesResetEvent != null)
                this.dnsGetHostAddressesResetEvent.WaitOne();
            this.retries = 0;
            this.client.BeginConnect(this.addresses, this.port, this.ClientConnectCallback, null);
        }

        /// <summary>
        /// Writes a string to the server using a given encoding.
        /// </summary>
        /// <param name="value">The string to write.</param>
        /// <param name="encoding">The encoding to use.</param>
        /// <returns>A Guid that can be used to match the data written to the confirmation event.</returns>
        public Guid Write(string value, Encoding encoding)
        {
            byte[] buffer = encoding.GetBytes(value);
            return this.Write(buffer);
        }

        /// <summary>
        /// Writes a byte array to the server.
        /// </summary>
        /// <param name="buffer">The byte array to write.</param>
        /// <returns>A Guid that can be used to match the data written to the confirmation event.</returns>
        public Guid Write(byte[] buffer)
        {
            Guid guid = Guid.NewGuid();
            NetworkStream networkStream = this.client.GetStream();
            networkStream.BeginWrite(buffer, 0, buffer.Length, this.ClientWriteCallback, guid);
            return guid;
        }

        /// <summary>
        /// Callback from the asynchronous DNS lookup.
        /// </summary>
        /// <param name="asyncResult">The result of the async operation.</param>
        private void DnsGetHostAddressesCallback(IAsyncResult asyncResult)
        {
            try
            {
                this.addresses = Dns.EndGetHostAddresses(asyncResult);
                this.dnsGetHostAddressesResetEvent.Set();
            }
            catch (Exception ex)
            {
                if (this.DnsGetHostAddressesException != null)
                    this.DnsGetHostAddressesException(this, new ExceptionEventArgs(ex));
            }
        }

        /// <summary>
        /// Callback from the asynchronous Connect method.
        /// </summary>
        /// <param name="asyncResult">The result of the async operation.</param>
        private void ClientConnectCallback(IAsyncResult asyncResult)
        {
            try
            {
                this.client.EndConnect(asyncResult);
                if (this.Connected != null)
                    this.Connected(this, new EventArgs());
            }
            catch (Exception ex)
            {
                retries++;
                if (retries < 3)
                {
                    this.client.BeginConnect(this.addresses, this.port, this.ClientConnectCallback, null);
                }
                else
                {
                    if (this.ClientConnectException != null)
                        this.ClientConnectException(this, new ExceptionEventArgs(ex));
                }
                return;
            }

            try
            {
                NetworkStream networkStream = this.client.GetStream();
                byte[] buffer = new byte[this.clientReadBufferLength];
                networkStream.BeginRead(buffer, 0, buffer.Length, this.ClientReadCallback, buffer);
            }
            catch (Exception ex)
            {
                if (this.ClientReadException != null)
                    this.ClientReadException(this, new ExceptionEventArgs(ex));
            }
        }

        /// <summary>
        /// Callback from the asynchronous Read method.
        /// </summary>
        /// <param name="asyncResult">The result of the async operation.</param>
        private void ClientReadCallback(IAsyncResult asyncResult)
        {
            try
            {
                NetworkStream networkStream = this.client.GetStream();
                int read = networkStream.EndRead(asyncResult);

                if (read == 0)
                {
                    if (this.Disconnected != null)
                        this.Disconnected(this, new EventArgs());
                }

                byte[] buffer = asyncResult.AsyncState as byte[];
                if (buffer != null)
                {
                    byte[] data = new byte[read];
                    Buffer.BlockCopy(buffer, 0, data, 0, read);
                    networkStream.BeginRead(buffer, 0, buffer.Length, this.ClientReadCallback, buffer);
                    if (this.DataRead != null)
                        this.DataRead(this, new DataReadEventArgs(data));
                }
            }
            catch (Exception ex)
            {
                if (this.ClientReadException != null)
                    this.ClientReadException(this, new ExceptionEventArgs(ex));
            }
        }

        /// <summary>
        /// Callback from the asynchronous write callback.
        /// </summary>
        /// <param name="asyncResult">The result of the async operation.</param>
        private void ClientWriteCallback(IAsyncResult asyncResult)
        {
            try
            {
                NetworkStream networkStream = this.client.GetStream();
                networkStream.EndWrite(asyncResult);
                Guid guid = (Guid)asyncResult.AsyncState;
                if (this.DataWritten != null)
                    this.DataWritten(this, new DataWrittenEventArgs(guid));
            }
            catch (Exception ex)
            {
                if (this.ClientWriteException != null)
                    this.ClientWriteException(this, new ExceptionEventArgs(ex));
            }
        }
    }

    /// <summary>
    /// Provides data for an exception occuring event.
    /// </summary>
    public class ExceptionEventArgs : EventArgs
    {
        /// <summary>
        /// Constructor for a new Exception Event Args object.
        /// </summary>
        /// <param name="ex">The exception that was thrown.</param>
        public ExceptionEventArgs(Exception ex)
        {
            this.Exception = ex;
        }

        public Exception Exception { get; private set; }
    }

    /// <summary>
    /// Provides data for a data read event.
    /// </summary>
    public class DataReadEventArgs : EventArgs
    {
        /// <summary>
        /// Constructor for a new Data Read Event Args object.
        /// </summary>
        /// <param name="data">The data that was read from the remote host.</param>
        public DataReadEventArgs(byte[] data)
        {
            this.Data = data;
        }

        /// <summary>
        /// Gets the data that has been read.
        /// </summary>
        public byte[] Data { get; private set; }
    }

    /// <summary>
    /// Provides data for a data write event.
    /// </summary>
    public class DataWrittenEventArgs : EventArgs
    {
        /// <summary>
        /// Constructor for a Data Written Event Args object.
        /// </summary>
        /// <param name="guid">The guid of the data written.</param>
        public DataWrittenEventArgs(Guid guid)
        {
            this.Guid = guid;
        }

        /// <summary>
        /// Gets the Guid used to match the data written to the confirmation event.
        /// </summary>
        public Guid Guid { get; private set; }
    }
}

This is what I’ve tried but I don’t get it. I’m new to c#:

using System;
using System.Text;
using System.Threading;

namespace asynchronous
{
    class Program
    {
        private static EventHandler connection;
        private static EventHandler<DataReadEventArgs> irc_DataRead;
        static void Main(string[] args)
        {
            var irc = new Client("irc.rizon.net", 6667);
            Console.WriteLine("Connecting...");
            irc.Connect();
            Thread.Sleep(2000);
            irc.Write("Test", Encoding.UTF8);
            irc.DataRead+=new EventHandler<DataReadEventArgs>(irc_DataRead);
            Console.WriteLine(irc_DataRead);
            Console.WriteLine("Connected.");
            Console.ReadLine();
        }
    }
}

Could someone please help me setup that class to connect to IRC and read and write text?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T06:09:32+00:00Added an answer on May 28, 2026 at 6:09 am

    Here you are hooking up a null instance of an event handler into an event. You need to hookup an actual method / lambda in order for this to work. Try the following

    static void OnDataRead(object sender, DataReadEventArgs e) {
      // Data reads call this method
    }
    
    
    static void Main(string[] args) {
      ...
      irc.DataRead += OnDataRead;
      ...
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

this is the code that i have found in the internet for reading the
Firstly, I've never used threads, but have found lots of examples on the internet
I'm trying this code I found with google, but it didn't connect to my
I'm appalled I haven't found anything on the internet about this problem, but probably
I found this code here class Usable; class Usable_lock { friend class Usable; private:
I found one source which successfully overrode Time.strftime like this: class Time alias :old_strftime
Here I found this code: import java.awt.*; import javax.swing.*; public class FunWithPanels extends JFrame
Found this: Sub SurroundWithAppendTag() DTE.ActiveDocument.Selection.Text = .Append( + DTE.ActiveDocument.Selection.Text + ) End Sub But
Reading this question I found this as (note the quotation marks) code to solve
I found this link http://artis.imag.fr/~Xavier.Decoret/resources/glsl-mode/ , but there isn't a lot of description around

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.