matthileo

Untitled

Aug 17th, 2016
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 5.01 KB | None | 0 0
  1. using System;
  2. using System.Text;
  3. using System.Net.Sockets;
  4. using System.Threading;
  5. using System.Net;
  6.  
  7.  
  8. namespace kmserv
  9. {
  10.   class Server
  11.   {
  12.         private TcpListener tcpListener;
  13.         private Thread listenThread;
  14.         private TcpClient tcpClient;
  15.        
  16.         public static void Main (string[] args)
  17.         {
  18.            
  19.             Server kmserv = new Server(23569);
  20.         }
  21.        
  22.         public Server(int port)
  23.         {
  24.             Console.WriteLine ("Starting kmserv on port "+port.ToString()+"...");
  25.             this.tcpListener = new TcpListener(IPAddress.Any, port);
  26.             this.listenThread = new Thread(new ThreadStart(ListenForClients));
  27.             this.listenThread.Start();
  28.         }
  29.        
  30.         private void ListenForClients()
  31.         {
  32.             this.tcpListener.Start();
  33.             while (true)
  34.             {
  35.                 //blocks until a client has connected to the server
  36.                 TcpClient client = this.tcpListener.AcceptTcpClient();
  37.                 //create a thread to handle communication
  38.                 //with connected client
  39.                 Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
  40.                 clientThread.Start(client);
  41.             }
  42.         }
  43.        
  44.         private void HandleClientComm(object client)
  45.         {
  46.             tcpClient = (TcpClient)client;
  47.             NetworkStream clientStream = tcpClient.GetStream();
  48.            
  49.             byte[] message = new byte[40960];
  50.             int bytesRead;
  51.             while (true)
  52.             {
  53.                 bytesRead = 0;
  54.                 try
  55.                 {
  56.                     //blocks until a client sends a message
  57.                     bytesRead = clientStream.Read(message, 0, 40960);
  58.                 }
  59.                 catch
  60.                 {
  61.                     //a socket error has occured
  62.                     break;
  63.                 }
  64.                
  65.                 if (bytesRead == 0)
  66.                 {
  67.                     //the client has disconnected from the server
  68.                     break;
  69.                 }
  70.                 //message has successfully been received
  71.                 ASCIIEncoding encoder = new ASCIIEncoding();
  72.                 //System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead));
  73.                 Console.WriteLine(GetCurrentTime() + " " + tcpClient.Client.RemoteEndPoint.ToString() + " [RECEIVED] | "+ encoder.GetString(message,0,bytesRead).Replace("\n",""));
  74.                 string command = encoder.GetString(message,0,bytesRead);
  75.                
  76.                 string reply=ParseCommand(command);
  77.                 SendReply(reply);
  78.                 Console.WriteLine(GetCurrentTime() + " " + tcpClient.Client.RemoteEndPoint.ToString() + " [SENT] | "+ reply);
  79.             }
  80.            
  81.             tcpClient.Close();
  82.         }
  83.        
  84.         private string ParseCommand(string command)
  85.         {
  86.             string reply="";
  87.             string prefix = command.Substring(0,3);
  88.             switch(prefix)
  89.             {
  90.             case "cmd":
  91.                 reply = ExecuteCommandSync(command.Substring(4));
  92.                 break;
  93.             default:
  94.                 reply = "ERROR: Invalid Command";
  95.                 break;
  96.             }
  97.             return reply;
  98.         }
  99.        
  100.         private void SendReply(string reply)
  101.         {
  102.             string tempEnd="\n";
  103.             System.Net.Sockets.NetworkStream clientStream = tcpClient.GetStream();
  104.             ASCIIEncoding encoder = new ASCIIEncoding();
  105.             byte[] buffer = encoder.GetBytes(reply+tempEnd);
  106.            
  107.             clientStream.Write(buffer, 0 , buffer.Length);
  108.             clientStream.Flush();
  109.         }
  110.        
  111.         private string GetCurrentTime()
  112.         {
  113.             string date = System.DateTime.Now.Year.ToString() +"-";
  114.             if (System.DateTime.Now.Month.ToString().Length==1)
  115.                 date +="0";
  116.             date +=System.DateTime.Now.Month.ToString() + "-";
  117.             if (System.DateTime.Now.Day.ToString().Length==1)
  118.                 date +="0";
  119.             date+=System.DateTime.Now.Day.ToString();
  120.            
  121.             date +=" ";
  122.            
  123.             if (System.DateTime.Now.Hour.ToString().Length==1)
  124.                 date+="0";
  125.             date += System.DateTime.Now.Hour.ToString()+":";
  126.             if (System.DateTime.Now.Minute.ToString().Length==1)
  127.                 date+="0";
  128.             date += System.DateTime.Now.Minute.ToString()+":";
  129.             if (System.DateTime.Now.Second.ToString().Length==1)
  130.                 date+="0";
  131.             date+=System.DateTime.Now.Second.ToString();
  132.             return date;
  133.         }
  134.        
  135.        
  136.         public string ExecuteCommandSync(object command)
  137.         {
  138.             string result="";
  139.            
  140.             try
  141.             {
  142.                  // create the ProcessStartInfo using "cmd" as the program to be run,
  143.                  // and "/c " as the parameters.
  144.                  // Incidentally, /c tells cmd that we want it to execute the command that follows,
  145.                  // and then exit.
  146.                 System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command.ToString().Replace("\n",""));
  147.                 //System.Diagnostics.ProcessStartInfo procStartInfo =   new System.Diagnostics.ProcessStartInfo();
  148.  
  149.                 // The following commands are needed to redirect the standard output.
  150.                 // This means that it will be redirected to the Process.StandardOutput StreamReader.
  151.                 procStartInfo.RedirectStandardOutput = true;
  152.                 procStartInfo.UseShellExecute = false;
  153.                 // Do not create the black window.
  154.                 procStartInfo.CreateNoWindow = true;
  155.                 // Now we create a process, assign its ProcessStartInfo and start it
  156.                 System.Diagnostics.Process proc = new System.Diagnostics.Process();
  157.                 proc.StartInfo = procStartInfo;
  158.                 proc.Start();
  159.                 // Get the output into a string
  160.                 result = proc.StandardOutput.ReadToEnd();
  161.                
  162.             }
  163.             catch (Exception objException)
  164.             {
  165.                 result =  objException.Message.ToString();
  166.             }
  167.             return result;
  168.         }
  169.    
  170.     }
  171. }
Advertisement
Add Comment
Please, Sign In to add comment