Friday, January 6, 2017

A Simple TCP listening Server - .Net core application

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

namespace TCPServerAndClient
{
    public class Program
    {
        public static void Main(string[] args)
        {
            TcpServer();
        }
     
//thought here is, code as simple as possible so that for beginners it should be easy to grasp the concept quickly.

        public static void TcpServer()
        {
             
                IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
                IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 1234); //ipaddress : is like Hotel name, you are intended to deliver msg only to this hotel. Port number: tells inside that hotel to which particular room you want to send  msg

                // Create a TCP/IP socket.
                Socket listener = new Socket(AddressFamily.InterNetwork,
                    SocketType.Stream, ProtocolType.Tcp);

               try
                {
                    listener.Bind(localEndPoint); //start listening for msg
                    listener.Listen(25); //The maximum length of the pending connections queue

                 
                    while (true)
                    {
                     
                        Socket handler = listener.Accept(); //snync call

                        byte[] requestBytes = new byte[handler.SendBufferSize]; //max bytes can  send by a client
                        handler.Receive(requestBytes);
                        string clientSentData = Encoding.ASCII.GetString(requestBytes); //convert bin to ascii, human readable format

                        Console.WriteLine($"This is what client sent {clientSentData}" );

                        string responseToClient = "Thank you, we got your request.";
                        byte[] responseBytes = Encoding.ASCII.GetBytes(responseToClient); //convert string to bin

                        handler.Send(responseBytes);
                        handler.Shutdown(SocketShutdown.Both);
                        handler.Dispose();
                    }

                }
                catch (Exception e)
                {
                    Console.WriteLine($" Oops something went wrong -> {e.ToString()} ");
                }

            }
 
    }
}