Click here to Skip to main content
Click here to Skip to main content

The Simplest TcpServer

, 19 Mar 2006 CPOL
Rate this:
Please Sign up or sign in to vote.
A really basic TCP server, just the core

Introduction

For a different project, I was looking for a TCP server example that I could use as a good starting point. I poked around the various TCP server articles here on The Code Project and didn't find anything that was simple enough! The articles I came across either required deriving specialized classes to handle the connection, were entangled with command processing, or were entangled with thread pool management.

What I wanted was a completely stand-alone, fire an event when a connection is established, TCP server. The event mechanism appeals to me because I can use the multicast delegate not only for processing the connection, but also to hook up monitoring/diagnostic handlers. There are, of course, issues that I don't discuss in this article, because that's not the point. Beginners are advised to read further on:

  • Managing TcpClient connections
  • Managed thread pools
  • Worker threads
  • TCP communication

However, the point is that with this server you can decide how your server manages the client connections rather than having some scheme foisted on you.

The Simplest TCP Server

So, here's the simplest TCP server. You can construct it by passing in:

  • An IPEndPoint
  • A port; the server will listen to IPAddress.Any for that port
  • An IP4 or IP6 address and a port

The Connected Event

The server application needs to hook one event, Connected, which is fired when a client connection is established. If there are no event handlers at the time the client connection is established, the TcpServer will immediately close the client connection. This event passes a ConnectionState instance, which is a simple wrapper for the Socket instance and the TcpServer instance:

using System;
using System.Net;
using System.Net.Sockets;

namespace Clifton.TcpLib
{
  /// <span class="code-SummaryComment"><summary></span>
  /// Buffers the socket connection and TcpServer instance.
  /// <span class="code-SummaryComment"></summary></span>
  public class ConnectionState
  {
    protected Socket connection;
    protected TcpServer server;

    /// <span class="code-SummaryComment"><summary></span>
    /// Gets the TcpServer instance. Throws an exception if the connection
    /// has been closed.
    /// <span class="code-SummaryComment"></summary></span>
    public TcpServer Server
    {
      get
      {
        if (server == null)
        {
          throw new TcpLibException("Connection is closed.");
      }

      return server; 
      }
    }

    /// <span class="code-SummaryComment"><summary></span>
    /// Gets the socket connection. Throws an exception if the connection
    /// has been closed.
    /// <span class="code-SummaryComment"></summary></span>
    public Socket Connection
    {
      get
      {
        if (server == null)
        {
          throw new TcpLibException("Connection is closed.");
        }

        return connection; 
      }
    }

    /// <span class="code-SummaryComment"><summary></span>
    /// Constructor.
    /// <span class="code-SummaryComment"></summary></span>
    /// <span class="code-SummaryComment"><param name="connection">The socket connection.</param></span>
    /// <span class="code-SummaryComment"><param name="server">The TcpServer instance.</param></span>
    public ConnectionState(Socket connection, TcpServer server)
    {
      this.connection = connection;
      this.server = server;
    }

    /// <span class="code-SummaryComment"><summary></span>
    /// This is the prefered manner for closing a socket connection, as it
    /// nulls the internal fields so that subsequently referencing a closed
    /// connection throws an exception. This method also throws an exception 
    /// if the connection has already been shut down.
    /// <span class="code-SummaryComment"></summary></span>
    public void Close()
    {
      if (server == null)
      {
        throw new TcpLibException("Connection already is closed.");
      }

      connection.Shutdown(SocketShutdown.Both);
      connection.Close();
      connection = null;
      server = null;
      }
    }
  }
}

The ConnectionState instance can be used by your communication code throughout the lifetime of the connection. Ideally, you would want to use the Close method of ConnectionState, as this also clears the internal fields so that you can't accidentally use the ConnectionState instance after the connection has been closed.

The HandleApplicationException Event

Optionally, you can also hook the HandleApplicationException event, which is useful when developing your application and detecting exceptions that you inadvertently forgot to catch yourself.

The TcpServer Class

The TcpServer provides two methods:

  • StartListening
  • StopListening

StartListening is used to begin listening to the IP address and port. This method is non-blocking, meaning that the method returns immediately rather than waiting for a connection to be established. Therefore it is the responsibility of the application to stay alive to receive connections.

The StopListening method is used to stop listening to the IP address and port. This method locks on the TcpServer instance so that it doesn't stop listening in the middle of accepting a new connection. The code for the connection acceptance also locks on the TcpServer instance. Two virtual methods implement the OnConnected and OnHandleApplicationException events calls, which is the standard .NET approach for calling events. Here's the code:

using System;
using System.Net;
using System.Net.Sockets;

// Loosely based on the article 
// http://www.codeproject.com/csharp/BasicTcpServer.asp

namespace Clifton.TcpLib
{
  /// <span class="code-SummaryComment"><summary></span>
  /// Implements the core of a TcpServer socket listener. This class makes no 
  /// assumptions regarding thread pool implementation, I/O interface such as
  /// streaming, command processing or connection management.
  /// Those details are left to the application.
  /// <span class="code-SummaryComment"></summary></span>
   public class TcpServer
   {
     public delegate void TcpServerEventDlgt(object sender, 
                                               TcpServerEventArgs e);
     public delegate void ApplicationExceptionDlgt(object sender, 
           TcpLibApplicationExceptionEventArgs e);

     /// <span class="code-SummaryComment"><summary></span>
     /// Event fires when a connection is accepted. Being multicast, this 
     /// allows you to attach not only your application's event handler, but
     /// also other handlers, such as diagnostics/monitoring, to the event.
     /// <span class="code-SummaryComment"></summary></span>
     public event TcpServerEventDlgt Connected;

     /// <span class="code-SummaryComment"><summary></span>
     /// This event fires when *your* application throws an exception 
     /// that *you* do not handle in the 
     /// interaction with the client. You can hook this event to log 
     /// unhandled exceptions, more as a 
     /// tool to aid development rather than a suggested approach 
     /// for handling your application errors.
     /// <span class="code-SummaryComment"></summary></span>
     public event ApplicationExceptionDlgt HandleApplicationException;

     protected IPEndPoint endPoint;
     protected Socket listener;
     protected int pendingConnectionQueueSize;

     /// <span class="code-SummaryComment"><summary></span>
     /// Gets/sets pendingConnectionQueueSize. The default is 100.
     /// <span class="code-SummaryComment"></summary></span>
     public int PendingConnectionQueueSize
     {
       get { return pendingConnectionQueueSize; }
       set
       {
         if (listener != null)
         {
           throw new TcpLibException("Listener has already started. 
                Changing the pending queue size is not allowed.");
         }

         pendingConnectionQueueSize = value; 
       }
     }

    /// <span class="code-SummaryComment"><summary></span>
    /// Gets listener socket.
    /// <span class="code-SummaryComment"></summary></span>
    public Socket Listener
    {
      get { return listener; }
    }

    /// <span class="code-SummaryComment"><summary></span>
    /// Gets/sets endPoint
    /// <span class="code-SummaryComment"></summary></span>
    public IPEndPoint EndPoint
    {
      get { return endPoint; }
      set
      {
        if (listener != null)
        {
          throw new TcpLibException("Listener has already 
              started. Changing the endpoint is not allowed.");
        }

        endPoint = value; 
      }
    }
 
    /// <span class="code-SummaryComment"><summary></span>
    /// Default constructor.
    /// <span class="code-SummaryComment"></summary></span>
    public TcpServer()
    {
      pendingConnectionQueueSize = 100;
    }

    /// <span class="code-SummaryComment"><summary></span>
    /// Initializes the server with an endpoint.
    /// <span class="code-SummaryComment"></summary></span>
    /// <span class="code-SummaryComment"><param name="endpoint"></param></span>
    public TcpServer(IPEndPoint endpoint)
    {
      this.endPoint = endpoint;
      pendingConnectionQueueSize = 100;
    }

    /// <span class="code-SummaryComment"><summary></span>
    /// Initializes the server with a port, the endpoint is initialized
    /// with IPAddress.Any.
    /// <span class="code-SummaryComment"></summary></span>
    /// <span class="code-SummaryComment"><param name="port"></param></span>
    public TcpServer(int port)
    {
      endPoint = new IPEndPoint(IPAddress.Any, port);
      pendingConnectionQueueSize = 100;
    }

    /// <span class="code-SummaryComment"><summary></span>
    /// Initializes the server with a 4 digit IP address and port.
    /// <span class="code-SummaryComment"></summary></span>
    /// <span class="code-SummaryComment"><param name="address"></param></span>
    /// <span class="code-SummaryComment"><param name="port"></param></span>
    public TcpServer(string address, int port)
    {
      endPoint = new IPEndPoint(IPAddress.Parse(address), port);
      pendingConnectionQueueSize = 100;
    }

    /// <span class="code-SummaryComment"><summary></span>
    /// Begins listening for incoming connections.
    /// This method returns immediately.
    /// Incoming connections are reported using the Connected event.
    /// <span class="code-SummaryComment"></summary></span>
    public void StartListening()
    {
      if (endPoint == null)
      {
        throw new TcpLibException("EndPoint not initialized.");
      }

      if (listener != null)
      {
        throw new TcpLibException("Already listening.");
      }

      listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, 
            ProtocolType.Tcp);
      listener.Bind(endPoint);
      listener.Listen(pendingConnectionQueueSize);
      listener.BeginAccept(AcceptConnection, null);
    }

    /// <span class="code-SummaryComment"><summary></span>
    /// Shuts down the listener.
    /// <span class="code-SummaryComment"></summary></span>
    public void StopListening()
    {
      // Make sure we're not accepting a connection.
      lock (this)
      {
        listener.Close();
        listener = null;
      }
    }

    /// <span class="code-SummaryComment"><summary></span>
    /// Accepts the connection and invokes any Connected event handlers.
    /// <span class="code-SummaryComment"></summary></span>
    /// <span class="code-SummaryComment"><param name="res"></param></span>
    protected void AcceptConnection(IAsyncResult res)
    {
      Socket connection;

      // Make sure listener doesn't go null on us.
      lock (this)
      {
        connection = listener.EndAccept(res);
        listener.BeginAccept(AcceptConnection, null);
      }

      // Close the connection if there are no handlers to accept it!
      if (Connected == null)
      {
        connection.Close();
      }
      else
      {
        ConnectionState cs = new ConnectionState(connection, this);
        OnConnected(new TcpServerEventArgs(cs));
      }
    }

    /// <span class="code-SummaryComment"><summary></span>
    /// Fire the Connected event if it exists.
    /// <span class="code-SummaryComment"></summary></span>
    /// <span class="code-SummaryComment"><param name="e"></param></span>
    protected virtual void OnConnected(TcpServerEventArgs e)
    {
      if (Connected != null)
      {
    try
        {
          Connected(this, e);
        }
        catch (Exception ex)
        {
          // Close the connection if the application threw an exception that
          // is caught here by the server.
          e.ConnectionState.Close();
          TcpLibApplicationExceptionEventArgs appErr = 
               new TcpLibApplicationExceptionEventArgs(ex);

          try
          {
            OnHandleApplicationException(appErr);
          }
          catch (Exception ex2)
          {
            // Oh great, the exception handler threw an exception!
            System.Diagnostics.Trace.WriteLine(ex2.Message);
          }
        }
      }
    }
  }
}

So, that's it. Granted, it isn't that simple because of the non-blocking listener and the exception handling, which really adds robustness to the server.

Example

A simple TcpServer example requires only a few lines of code:

using System;
using System.Collections.Generic;
using System.Text;

using Clifton.TcpLib;

namespace TcpServerDemo
{
  class Program
  {
    static void Main(string[] args)
    {
      TcpServer tcpServer = new TcpServer("127.0.0.1", 14000);
      tcpServer.Connected += new TcpServer.TcpServerEventDlgt(OnConnected);
      tcpServer.StartListening();
      Console.WriteLine("Press ENTER to exit the server.");
      Console.ReadLine();
      tcpServer.StopListening();
    }

    static void OnConnected(object sender, TcpServerEventArgs e)
    {
      // Handle the connection here by starting your own worker thread
      // that handles communicating with the client.
      Console.WriteLine("Connected.");
    }
  }
}

This code initializes the TcpServer to listen to the localhost address on port number 14000. Any time a client connects, it writes out "Connected." to the console window. If you press Enter, it stops the listener and exits the demo. The client side is even simpler, but of course, all it does right now is create the connection and then close it! Of course, your program would do something more than this:

using System;
using System.Net.Sockets;

namespace TcpClientDemo
{
  class Program
  {
    static void Main(string[] args)
    {
      TcpClient tcpClient = new TcpClient();
      tcpClient.Connect("127.0.0.1", 14000);
      tcpClient.Close();
    }
  }
}

Conclusion

I put this article in the Beginner section, as it is a core tutorial on TcpServer, using events and handling exceptions. If anyone finds any flaws in this approach, let me know, as I don't want to lead beginners astray! As you will see in future articles, this simple TcpServer will be used as a basis for working with a NetworkStream, GZipStream and CryptoStream.

Additional Reading

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Marc Clifton

United States United States
Marc is the creator of two open source projects, MyXaml, a declarative (XML) instantiation engine and the Advanced Unit Testing framework, and Interacx, a commercial n-tier RAD application suite.  Visit his website, www.marcclifton.com, where you will find many of his articles and his blog.
 
Marc lives in Philmont, NY.

Comments and Discussions

 
QuestionNice Article Pinmembershaijujanardhanan26-Nov-13 1:33 
QuestionThank you! PinmemberOption Greek24-Jun-11 5:30 
General5! PinmvpJohn Simmons / outlaw programmer1-Oct-08 6:41 
QuestionDoes anybody have an example for me? Pinmembervschwarz30-Apr-08 0:45 
AnswerRe: Does anybody have an example for me? PinprotectorMarc Clifton30-Apr-08 1:59 
GeneralRe: Does anybody have an example for me? [modified] Pinmembervschwarz30-Apr-08 2:02 
GeneralRe: Does anybody have an example for me? PinprotectorMarc Clifton30-Apr-08 3:28 
GeneralRe: Does anybody have an example for me? Pinmembervschwarz30-Apr-08 3:48 
GeneralRe: Does anybody have an example for me? PinprotectorMarc Clifton30-Apr-08 3:50 
Generalneed your help Pinmemberalexby8-Dec-07 12:34 
Generalexception handling in AcceptConnection [modified] PinmemberThosmos21-Aug-06 16:15 
GeneralRe: exception handling in AcceptConnection PinprotectorMarc Clifton22-Aug-06 3:11 
General[Message Deleted] PinmemberIan MacLean30-May-06 12:04 
GeneralRe: TcpServer vs. System.Net.TcpListener PinprotectorMarc Clifton30-May-06 16:13 
General[Message Deleted] PinmemberIan MacLean31-May-06 11:23 
GeneralRe: TcpServer vs. System.Net.TcpListener PinprotectorMarc Clifton31-May-06 14:19 
GeneralRe: TcpServer vs. System.Net.TcpListener PinprotectorMarc Clifton30-May-06 16:15 
QuestionWhere was this two years ago? PinmemberBenjamin Liedblad27-Mar-06 18:42 
AnswerRe: Where was this two years ago? PinmemberThe_Myth27-Mar-06 20:54 
GeneralRe: Where was this two years ago? PinsitebuilderUwe Keim31-Mar-06 8:47 
GeneralException handling PinmemberBlue Bird19-Mar-06 17:50 
GeneralRe: Exception handling PinprotectorMarc Clifton20-Mar-06 1:36 
GeneralRe: Exception handling PinmemberBlue Bird20-Mar-06 2:03 
GeneralRe: Exception handling PinprotectorMarc Clifton20-Mar-06 2:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.1411023.1 | Last Updated 19 Mar 2006
Article Copyright 2006 by Marc Clifton
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid