Komak57

ServerSockTest

Dec 26th, 2014
206
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 16.39 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Windows.Forms;
  9. using System.Net;
  10. using System.Net.Sockets;
  11. using System.Threading;
  12. using System.IO;
  13. using System.Text.RegularExpressions;
  14. using System.Diagnostics;
  15. using System.Runtime.InteropServices;
  16.  
  17. namespace TouchPadPro {
  18.  
  19.     public partial class Form1 : Form
  20.     {
  21.         [DllImport("user32.dll", SetLastError = true)]
  22.         public static extern bool SetCursorPos(int X, int Y);
  23.         [DllImport("user32.dll")]
  24.         public static extern bool GetCursorPos(out Point lpPoint);
  25.  
  26.         // The port number for the remote device.
  27.         private List<SockClient> clients = new List<SockClient>();
  28.         //private List<SockClient> clients = new List<SockClient>();
  29.  
  30.         private int _maxConnections = 10;
  31.         private Socket _listener;
  32.         private AsyncCallback ConnectionReady;
  33.         private WaitCallback AcceptConnection;
  34.  
  35.         public Form1()
  36.         {
  37.             InitializeComponent();
  38.         }
  39.  
  40.         private void Avitvated(object sender, EventArgs e)
  41.         {
  42.             IPHostEntry host;
  43.             string foundIP = "?";
  44.             host = Dns.GetHostEntry(Dns.GetHostName());
  45.             foreach (IPAddress ip in host.AddressList)
  46.             {
  47.                 if (ip.AddressFamily == AddressFamily.InterNetwork)
  48.                 {
  49.                     foundIP = ip.ToString();
  50.                 }
  51.             }
  52.             localIP.Text = foundIP;
  53.  
  54.             ConnectionReady = new AsyncCallback(ConnectionReady_Handler);
  55.             AcceptConnection = new WaitCallback(AcceptConnection_Handler);
  56.         }
  57.  
  58.         private void btnConnect_Click(object sender, EventArgs e)
  59.         {
  60.             if (btnConnect.Text == "Start")
  61.             {
  62.                 try
  63.                 {
  64.                     Console.WriteLine("[" + DateTime.Now.ToString("h:mm:ss") + "] Starting Server...");
  65.                     clients = new List<SockClient>();
  66.                     _listener = new Socket(AddressFamily.InterNetwork,
  67.                         SocketType.Stream, ProtocolType.Tcp);
  68.  
  69.  
  70.                     //_listener.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), int.Parse(localPort.Text)));
  71.                     _listener.Bind(new IPEndPoint(IPAddress.Parse(localIP.Text), int.Parse(localPort.Text)));
  72.                     _listener.Listen(_maxConnections);
  73.                     _listener.BeginAccept(ConnectionReady, null);
  74.  
  75.                     btnConnect.Text = "Stop";
  76.                 }
  77.                 catch (Exception ex)
  78.                 {
  79.                     Console.WriteLine("[" + DateTime.Now.ToString("h:mm:ss") + "] Startup failed: "+ex.ToString());
  80.                 }
  81.                 //pingTimer.Enabled = true;
  82.             }
  83.             else
  84.             {
  85.                 // kill all connections
  86.                 for(int i = 0; clients.Count > 0; i++)
  87.                 {
  88.                     try
  89.                     {
  90.                         clients[0].socket.Shutdown(SocketShutdown.Both);
  91.                         clients[0].socket.Close();
  92.                     }
  93.                     catch (Exception eignore)
  94.                     {
  95.                     }
  96.                 }
  97.  
  98.                 Disconnect();
  99.                 btnConnect.Text = "Start";
  100.                 //pingTimer.Enabled = false;
  101.             }
  102.         }
  103.  
  104.         public void Disconnect()
  105.         {
  106.             foreach (SockClient s in clients)
  107.             {
  108.                 s.OnDropConnection();
  109.             }
  110.             Console.WriteLine("[" + DateTime.Now.ToString("h:mm:ss") + "] Stopping Server...");
  111.             try { _listener.Shutdown(SocketShutdown.Both); }
  112.             catch (Exception e1) { }
  113.             try { _listener.Close(); }
  114.             catch (Exception e2) { }
  115.         }
  116.  
  117.         public void EndConnection(SockClient st)
  118.         {
  119.             Console.WriteLine("[" + DateTime.Now.ToString("h:mm:ss") + "] "+st.IP+": Connection Ended.");
  120.             clients.Remove(st);
  121.         }
  122.  
  123.         private void ConnectionReady_Handler(IAsyncResult ar)
  124.         {
  125.             lock (this)
  126.             {
  127.                 Console.WriteLine("[" + DateTime.Now.ToString("h:mm:ss") + "] ConnectionReady_Handler()");
  128.                 if (_listener == null) return;
  129.                 try
  130.                 {
  131.                     Socket conn = _listener.EndAccept(ar);
  132.  
  133.                     // kill all dead connections
  134.                     /*for(int i = 0; i < clients.Count; i++)
  135.                     {
  136.                         if (!clients[i].socket.Connected)
  137.                         {
  138.                             clients[i].OnDropConnection();
  139.                             i--;
  140.                         }
  141.                     }*/
  142.  
  143.                     if (clients.Count >= _maxConnections)
  144.                     {
  145.                         Console.WriteLine("[" + DateTime.Now.ToString("h:mm:ss") + "] Client denied access: Busy");
  146.                         //Max number of connections reached.
  147.                         string msg = "SE001: Server busy";
  148.                         conn.Send(Encoding.UTF8.GetBytes(msg), 0,
  149.                         msg.Length, SocketFlags.None);
  150.                         conn.Shutdown(SocketShutdown.Both);
  151.                         conn.Close();
  152.                     }
  153.                     else
  154.                     {
  155.                         //Start servicing a new connection
  156.                         SockClient st = new SockClient(this, conn);
  157.                         st.nick = "Guest";
  158.                         st.IP = (conn.RemoteEndPoint as IPEndPoint).Address.ToString();
  159.                         st.textBuf = new byte[0];
  160.                         clients.Add(st);
  161.                         //Queue the rest of the job to be executed latter
  162.                         //ThreadPool.QueueUserWorkItem(TAcceptConnection, st);
  163.                         AcceptConnection_Handler(st);
  164.                     }
  165.                     //Resume the listening callback loop
  166.                     _listener.BeginAccept(ConnectionReady, null);
  167.                 }
  168.                 catch (ObjectDisposedException ode)
  169.                 {
  170.                     Console.WriteLine("[" + DateTime.Now.ToString("h:mm:ss") + "] Server Failure: "+ode.ToString());
  171.                     try { _listener.Shutdown(SocketShutdown.Both); } catch (Exception e1) { }
  172.                     try { _listener.Close(); } catch (Exception e2) { }
  173.                     btnConnect.Text = "Start";
  174.                 }
  175.             }
  176.         }
  177.  
  178.         /// <SUMMARY>
  179.         /// Executes OnAcceptConnection method from the service provider.
  180.         /// </SUMMARY>
  181.         private void AcceptConnection_Handler(object state)
  182.         {
  183.             Console.WriteLine("[" + DateTime.Now.ToString("h:mm:ss") + "] AcceptConnection_Handler()");
  184.             SockClient st = state as SockClient;
  185.             try {
  186.                 st.OnAcceptConnection();
  187.             }
  188.             catch (Exception e)
  189.             {
  190.                 //report error in provider... Probably to the EventLog
  191.                 Console.WriteLine("[" + DateTime.Now.ToString("h:mm:ss") + "] ERROR! " + e.ToString());
  192.             }
  193.         }
  194.  
  195.         public class SockClient
  196.         {
  197.             public Socket socket;
  198.             [NonSerialized]
  199.             public Form1 server;
  200.             public string IP;
  201.             public string nick;
  202.             public Thread ReceiveThread;
  203.             public Stopwatch pingtime;
  204.             public string data;
  205.             public byte[] textBuf;
  206.             PointF curPos;
  207.  
  208.             public SockClient(Form1 server, Socket socket)
  209.             {
  210.                 this.server = server;
  211.                 this.socket = socket;
  212.                 this.IP = (socket.RemoteEndPoint as IPEndPoint).Address.ToString();
  213.                 this.nick = "Unknown";
  214.                 pingtime = new Stopwatch();
  215.                 data = "";
  216.                 Point p;
  217.                 GetCursorPos(out p);
  218.                 curPos.X = p.X;
  219.                 curPos.Y = p.Y;
  220.             }
  221.  
  222.             public void OnAcceptConnection()
  223.             {
  224.                 Console.WriteLine("[" + DateTime.Now.ToString("h:mm:ss") + "] " + IP + " Client connected.");
  225.                 StartReadThread();
  226.             }
  227.  
  228.             public void OnReceiveData()
  229.             {
  230.                 String msg = Encoding.ASCII.GetString(textBuf);
  231.                 textBuf = new byte[0];
  232.  
  233.                 //Stopwatch stopwatch = new Stopwatch();
  234.                 //int c = 0;
  235.                 //stopwatch.Start();
  236.                 while (msg.Contains("\r\n"))
  237.                 {
  238.                     String cmd = msg.Substring(0, msg.IndexOf("\r\n"));
  239.                     // scrape out command
  240.                     msg = msg.Substring(cmd.Length + ("\r\n").Length);
  241.                     Handle(cmd);
  242.                     //c++;
  243.                 }
  244.                 //stopwatch.Stop();
  245.                 //Console.WriteLine("[" + DateTime.Now.ToString("h:mm:ss") + "] " + IP + " Handled " + c + " msgs in " + (stopwatch.ElapsedMilliseconds) + "ms (" + (stopwatch.ElapsedMilliseconds / c) + "ms per).");
  246.                 //textBuf = new byte[0];//Encoding.ASCII.GetBytes(msg);
  247.             }
  248.             public void Handle(String msg)
  249.             {
  250.                 String[] args = msg.Split(' ');
  251.                 switch (args[0])
  252.                 {
  253.                     case "MOVE":
  254.                         {
  255.                             float X = float.Parse(args[1]);
  256.                             float Y = float.Parse(args[2]);
  257.                             curPos.X += X; curPos.Y += Y;
  258.                             Cursor.Position = Point.Round(curPos);
  259.                             break;
  260.                         }
  261.                     case "LCLICK":
  262.                         {
  263.                             int state = int.Parse(args[2]);
  264.                             break;
  265.                         }
  266.                     case "RCLICK":
  267.                         {
  268.                             int state = int.Parse(args[2]);
  269.                             break;
  270.                         }
  271.                     default:
  272.                         Console.WriteLine("[" + DateTime.Now.ToString("h:mm:ss") + "] " + IP + ":? " + msg);
  273.                         break;
  274.                 }
  275.             }
  276.  
  277.             public void OnDropConnection()
  278.             {
  279.                 while (ReceiveThread.IsAlive)
  280.                     ReceiveThread.Interrupt();
  281.                 if (socket.Connected)
  282.                 {
  283.                     Send("Closing Connection.");
  284.                     socket.Shutdown(SocketShutdown.Both);
  285.                     socket.Close();
  286.                 }
  287.                 Console.WriteLine("[" + DateTime.Now.ToString("h:mm:ss") + "] " + IP + " Client dropped.");
  288.                 server.EndConnection(this);
  289.             }
  290.  
  291.             public void LiveCheck()
  292.             {
  293.                 if (socket.Connected)
  294.                     OnDropConnection();
  295.             }
  296.  
  297.             public void Send(string msg)
  298.             {
  299.                 try
  300.                 {
  301.                     // Encode the data string into a byte array.
  302.                     byte[] buf = Encoding.ASCII.GetBytes(msg + "\r\n");
  303.  
  304.                     // Send the data through the socket.
  305.                     int bytesSent = socket.Send(buf);
  306.  
  307.                     Console.WriteLine("[" + DateTime.Now.ToString("h:mm:ss") + "] " + IP + " Client denied access: Busy");
  308.                     //AddLog("<Server> -> " + clients[ID].nick + ": " + msg);
  309.                 }
  310.                 catch (Exception e)
  311.                 {
  312.                     // remove the list item
  313.                     server.EndConnection(this);
  314.                 }
  315.             }
  316.  
  317.             /// <SUMMARY>
  318.             /// Executes OnReceiveData method from the service provider.
  319.             /// </SUMMARY>
  320.             public void StartReadThread()
  321.             {
  322.                 ReceiveThread = new Thread(new ThreadStart(() =>
  323.                 {
  324.                     try
  325.                     {
  326.                         Console.WriteLine("[" + DateTime.Now.ToString("h:mm:ss") + "] Receiver opened.");
  327.                         while (socket.Connected)
  328.                         {
  329.                             int l = socket.Available;
  330.                             if (l > 0)
  331.                             {
  332.                                 Stopwatch counter = new Stopwatch();
  333.                                 counter.Start();
  334.                                 //Console.WriteLine("[" + DateTime.Now.ToString("h:mm:ss") + "] Receiver aquired "+l+" bytes.");
  335.                                 byte[] prev = textBuf;
  336.                                 byte[] rec = new byte[l];
  337.                                 // receive all and add to buffer
  338.                                 socket.Receive(rec);
  339.                                 textBuf = new byte[prev.Length + rec.Length];
  340.                                 System.Buffer.BlockCopy(prev, 0, textBuf, 0, prev.Length);
  341.                                 System.Buffer.BlockCopy(rec, 0, textBuf, prev.Length, rec.Length);
  342.                                 // handle received info
  343.                                 try
  344.                                 {
  345.                                     try
  346.                                     {
  347.                                         // send to handler
  348.                                         try
  349.                                         {
  350.                                             OnReceiveData();
  351.                                         }
  352.                                         catch (ObjectDisposedException e)
  353.                                         {
  354.                                             Console.WriteLine("[" + DateTime.Now.ToString("h:mm:ss") + "] " + IP + ":" + nick + " Diconnected(Connection Closed)");
  355.                                             return;
  356.                                         }
  357.                                     }
  358.                                     catch (Exception e)
  359.                                     {
  360.                                         Console.WriteLine("[" + DateTime.Now.ToString("h:mm:ss") + "] <" + IP + ":" + nick + "> Error handling data: " + e.ToString());
  361.                                     }
  362.                                 }
  363.                                 catch (Exception e)
  364.                                 {
  365.                                     //report error in the provider
  366.                                     Console.WriteLine("[" + DateTime.Now.ToString("h:mm:ss") + "] <" + IP + ":" + nick + "> Read Error! " + e.ToString());
  367.                                 }
  368.                                 Console.WriteLine("[" + DateTime.Now.ToString("h:mm:ss") + "] <" + IP + ":" + nick + "> Parsed " + l + "bytes in " + counter.ElapsedMilliseconds + "ms");
  369.                                 counter.Stop();
  370.                             }
  371.                             // sleep a moment and give it another run
  372.                             Thread.Sleep(1000/30); // tries 30 times a second
  373.                         }
  374.                         Console.WriteLine("[" + DateTime.Now.ToString("h:mm:ss") + "] " + IP + ":" + nick + " Disconnected(Client Lost)");
  375.                         try
  376.                         {
  377.                             OnDropConnection();
  378.                         }
  379.                         catch (ObjectDisposedException ode)
  380.                         {
  381.                         }
  382.                         return;
  383.                     }
  384.                     catch (ThreadInterruptedException e)
  385.                     {
  386.                         // trying to kill process
  387.                     }
  388.                     catch (Exception une)
  389.                     {
  390.                         Console.WriteLine("[" + DateTime.Now.ToString("h:mm:ss") + "] " + IP + ":" + nick + " Unexpected Reader Error: " + une.ToString());
  391.                     }
  392.  
  393.                     try
  394.                     {
  395.                         OnDropConnection();
  396.                         return;
  397.                     }
  398.                     catch (ObjectDisposedException ode)
  399.                     {
  400.                     }
  401.  
  402.                     Console.WriteLine("[" + DateTime.Now.ToString("h:mm:ss") + "] " + IP + ":" + nick + " Read thread ended!");
  403.                 }));
  404.                 ReceiveThread.Start();
  405.             }
  406.         }
  407.     }
  408. }
Advertisement
Add Comment
Please, Sign In to add comment