Server Side example

Create Listener for server

Start of with creating an server that will handle clients that connect, and requests that will be send. So create an Listener Class that will handle this.

class Listener
{
    public Socket ListenerSocket; //This is the socket that will listen to any incoming connections
    public short Port = 1234; // on this port we will listen

    public Listener()
    {
        ListenerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    }
 }

First we need to initialize the Listener socket where we can listen on for any connections. We are going to use an Tcp Socket that is why we use SocketType.Stream. Also we specify to witch port the server should listen to

Then we start listening for any incoming connections.

The tree methods we use here are:

  1. ListenerSocket.Bind();

This method binds the socket to an IPEndPoint. This class contains the host and local or remote port information needed by an application to connect to a service on a host.

  1. ListenerSocket.Listen(10);

The backlog parameter specifies the number of incoming connections that can be queued for acceptance.

  1. ListenerSocket.BeginAccept();

The server will start listening for incoming connections and will go on with other logic. When there is an connection the server switches back to this method and will run the AcceptCallBack methodt

public void StartListening()
    {
        try
        {                
                MessageBox.Show($"Listening started port:{Port} protocol type: {ProtocolType.Tcp}");                    
                ListenerSocket.Bind(new IPEndPoint(IPAddress.Any, Port));
                ListenerSocket.Listen(10);
                ListenerSocket.BeginAccept(AcceptCallback, ListenerSocket);                
        }
        catch(Exception ex)
        {
            throw new Exception("listening error" + ex);
        }
    }

So when a client connects we can accept them by this method:

Three methods wee use here are:

  1. ListenerSocket.EndAccept()

We started the callback with Listener.BeginAccept() end now we have to end that call back. The EndAccept() method accepts an IAsyncResult parameter, this will store the state of the asynchronous method, From this state we can extract the socket where the incoming connection was coming from.

  1. ClientController.AddClient()

With the socket we got from EndAccept() we create an Client with an own made method (code ClientController below server example).