Click here to Skip to main content
15,867,939 members
Articles / Programming Languages / C#
Article

The Simplest TcpServer

Rate me:
Please Sign up or sign in to vote.
4.69/5 (29 votes)
19 Mar 2006CPOL3 min read 177.5K   4.9K   138   27
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:

C#
using System;
using System.Net;
using System.Net.Sockets;

namespace Clifton.TcpLib
{
  /// <summary>
  /// Buffers the socket connection and TcpServer instance.
  /// </summary>
  public class ConnectionState
  {
    protected Socket connection;
    protected TcpServer server;

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

      return server; 
      }
    }

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

        return connection; 
      }
    }

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

    /// <summary>
    /// 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.
    /// </summary>
    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:

C#
using System;
using System.Net;
using System.Net.Sockets;

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

namespace Clifton.TcpLib
{
  /// <summary>
  /// 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.
  /// </summary>
   public class TcpServer
   {
     public delegate void TcpServerEventDlgt(object sender, 
                                               TcpServerEventArgs e);
     public delegate void ApplicationExceptionDlgt(object sender, 
           TcpLibApplicationExceptionEventArgs e);

     /// <summary>
     /// 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.
     /// </summary>
     public event TcpServerEventDlgt Connected;

     /// <summary>
     /// 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.
     /// </summary>
     public event ApplicationExceptionDlgt HandleApplicationException;

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

     /// <summary>
     /// Gets/sets pendingConnectionQueueSize. The default is 100.
     /// </summary>
     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; 
       }
     }

    /// <summary>
    /// Gets listener socket.
    /// </summary>
    public Socket Listener
    {
      get { return listener; }
    }

    /// <summary>
    /// Gets/sets endPoint
    /// </summary>
    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; 
      }
    }
 
    /// <summary>
    /// Default constructor.
    /// </summary>
    public TcpServer()
    {
      pendingConnectionQueueSize = 100;
    }

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

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

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

    /// <summary>
    /// Begins listening for incoming connections.
    /// This method returns immediately.
    /// Incoming connections are reported using the Connected event.
    /// </summary>
    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);
    }

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

    /// <summary>
    /// Accepts the connection and invokes any Connected event handlers.
    /// </summary>
    /// <param name="res"></param>
    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));
      }
    }

    /// <summary>
    /// Fire the Connected event if it exists.
    /// </summary>
    /// <param name="e"></param>
    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:

C#
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:

C#
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)


Written By
Architect Interacx
United States United States
Blog: https://marcclifton.wordpress.com/
Home Page: http://www.marcclifton.com
Research: http://www.higherorderprogramming.com/
GitHub: https://github.com/cliftonm

All my life I have been passionate about architecture / software design, as this is the cornerstone to a maintainable and extensible application. As such, I have enjoyed exploring some crazy ideas and discovering that they are not so crazy after all. I also love writing about my ideas and seeing the community response. As a consultant, I've enjoyed working in a wide range of industries such as aerospace, boatyard management, remote sensing, emergency services / data management, and casino operations. I've done a variety of pro-bono work non-profit organizations related to nature conservancy, drug recovery and women's health.

Comments and Discussions

 
QuestionNEED AN URGENT REPLY .....PLZ HELP Pin
aayush saraswat4-Dec-14 20:19
aayush saraswat4-Dec-14 20:19 
AnswerRe: NEED AN URGENT REPLY .....PLZ HELP Pin
Marc Clifton6-Dec-14 15:06
mvaMarc Clifton6-Dec-14 15:06 
QuestionNice Article Pin
shaijujanardhanan26-Nov-13 0:33
shaijujanardhanan26-Nov-13 0:33 
QuestionThank you! Pin
Option Greek24-Jun-11 4:30
Option Greek24-Jun-11 4:30 
General5! Pin
#realJSOP1-Oct-08 5:41
mve#realJSOP1-Oct-08 5:41 
QuestionDoes anybody have an example for me? Pin
vschwarz29-Apr-08 23:45
vschwarz29-Apr-08 23:45 
AnswerRe: Does anybody have an example for me? Pin
Marc Clifton30-Apr-08 0:59
mvaMarc Clifton30-Apr-08 0:59 
GeneralRe: Does anybody have an example for me? [modified] Pin
vschwarz30-Apr-08 1:02
vschwarz30-Apr-08 1:02 
GeneralRe: Does anybody have an example for me? Pin
Marc Clifton30-Apr-08 2:28
mvaMarc Clifton30-Apr-08 2:28 
GeneralRe: Does anybody have an example for me? Pin
vschwarz30-Apr-08 2:48
vschwarz30-Apr-08 2:48 
GeneralRe: Does anybody have an example for me? Pin
Marc Clifton30-Apr-08 2:50
mvaMarc Clifton30-Apr-08 2:50 
GeneralRe: Does anybody have an example for me? Pin
Andreas Reitberger18-Jun-20 2:20
Andreas Reitberger18-Jun-20 2:20 
Generalneed your help Pin
alexby8-Dec-07 11:34
alexby8-Dec-07 11:34 
Generalexception handling in AcceptConnection [modified] Pin
Thosmos21-Aug-06 15:15
Thosmos21-Aug-06 15:15 
GeneralRe: exception handling in AcceptConnection Pin
Marc Clifton22-Aug-06 2:11
mvaMarc Clifton22-Aug-06 2:11 
General[Message Deleted] Pin
Ian MacLean30-May-06 11:04
Ian MacLean30-May-06 11:04 
GeneralRe: TcpServer vs. System.Net.TcpListener Pin
Marc Clifton30-May-06 15:13
mvaMarc Clifton30-May-06 15:13 
General[Message Deleted] Pin
Ian MacLean31-May-06 10:23
Ian MacLean31-May-06 10:23 
GeneralRe: TcpServer vs. System.Net.TcpListener Pin
Marc Clifton31-May-06 13:19
mvaMarc Clifton31-May-06 13:19 
GeneralRe: TcpServer vs. System.Net.TcpListener Pin
Marc Clifton30-May-06 15:15
mvaMarc Clifton30-May-06 15:15 
QuestionWhere was this two years ago? Pin
Benjamin Liedblad27-Mar-06 17:42
Benjamin Liedblad27-Mar-06 17:42 
AnswerRe: Where was this two years ago? Pin
AnasHashki27-Mar-06 19:54
AnasHashki27-Mar-06 19:54 
GeneralRe: Where was this two years ago? Pin
Uwe Keim31-Mar-06 7:47
sitebuilderUwe Keim31-Mar-06 7:47 
GeneralException handling Pin
Blue Bird19-Mar-06 16:50
Blue Bird19-Mar-06 16:50 
GeneralRe: Exception handling Pin
Marc Clifton20-Mar-06 0:36
mvaMarc Clifton20-Mar-06 0:36 

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

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