Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
- using System.Net;
- using System.Net.Sockets;
- using System.Threading;
- using System.IO;
- using System.Text.RegularExpressions;
- using System.Diagnostics;
- using System.Runtime.InteropServices;
- namespace TouchPadPro {
- public partial class Form1 : Form
- {
- [DllImport("user32.dll", SetLastError = true)]
- public static extern bool SetCursorPos(int X, int Y);
- [DllImport("user32.dll")]
- public static extern bool GetCursorPos(out Point lpPoint);
- // The port number for the remote device.
- private List<SockClient> clients = new List<SockClient>();
- //private List<SockClient> clients = new List<SockClient>();
- private int _maxConnections = 10;
- private Socket _listener;
- private AsyncCallback ConnectionReady;
- private WaitCallback AcceptConnection;
- public Form1()
- {
- InitializeComponent();
- }
- private void Avitvated(object sender, EventArgs e)
- {
- IPHostEntry host;
- string foundIP = "?";
- host = Dns.GetHostEntry(Dns.GetHostName());
- foreach (IPAddress ip in host.AddressList)
- {
- if (ip.AddressFamily == AddressFamily.InterNetwork)
- {
- foundIP = ip.ToString();
- }
- }
- localIP.Text = foundIP;
- ConnectionReady = new AsyncCallback(ConnectionReady_Handler);
- AcceptConnection = new WaitCallback(AcceptConnection_Handler);
- }
- private void btnConnect_Click(object sender, EventArgs e)
- {
- if (btnConnect.Text == "Start")
- {
- try
- {
- Console.WriteLine("[" + DateTime.Now.ToString("h:mm:ss") + "] Starting Server...");
- clients = new List<SockClient>();
- _listener = new Socket(AddressFamily.InterNetwork,
- SocketType.Stream, ProtocolType.Tcp);
- //_listener.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), int.Parse(localPort.Text)));
- _listener.Bind(new IPEndPoint(IPAddress.Parse(localIP.Text), int.Parse(localPort.Text)));
- _listener.Listen(_maxConnections);
- _listener.BeginAccept(ConnectionReady, null);
- btnConnect.Text = "Stop";
- }
- catch (Exception ex)
- {
- Console.WriteLine("[" + DateTime.Now.ToString("h:mm:ss") + "] Startup failed: "+ex.ToString());
- }
- //pingTimer.Enabled = true;
- }
- else
- {
- // kill all connections
- for(int i = 0; clients.Count > 0; i++)
- {
- try
- {
- clients[0].socket.Shutdown(SocketShutdown.Both);
- clients[0].socket.Close();
- }
- catch (Exception eignore)
- {
- }
- }
- Disconnect();
- btnConnect.Text = "Start";
- //pingTimer.Enabled = false;
- }
- }
- public void Disconnect()
- {
- foreach (SockClient s in clients)
- {
- s.OnDropConnection();
- }
- Console.WriteLine("[" + DateTime.Now.ToString("h:mm:ss") + "] Stopping Server...");
- try { _listener.Shutdown(SocketShutdown.Both); }
- catch (Exception e1) { }
- try { _listener.Close(); }
- catch (Exception e2) { }
- }
- public void EndConnection(SockClient st)
- {
- Console.WriteLine("[" + DateTime.Now.ToString("h:mm:ss") + "] "+st.IP+": Connection Ended.");
- clients.Remove(st);
- }
- private void ConnectionReady_Handler(IAsyncResult ar)
- {
- lock (this)
- {
- Console.WriteLine("[" + DateTime.Now.ToString("h:mm:ss") + "] ConnectionReady_Handler()");
- if (_listener == null) return;
- try
- {
- Socket conn = _listener.EndAccept(ar);
- // kill all dead connections
- /*for(int i = 0; i < clients.Count; i++)
- {
- if (!clients[i].socket.Connected)
- {
- clients[i].OnDropConnection();
- i--;
- }
- }*/
- if (clients.Count >= _maxConnections)
- {
- Console.WriteLine("[" + DateTime.Now.ToString("h:mm:ss") + "] Client denied access: Busy");
- //Max number of connections reached.
- string msg = "SE001: Server busy";
- conn.Send(Encoding.UTF8.GetBytes(msg), 0,
- msg.Length, SocketFlags.None);
- conn.Shutdown(SocketShutdown.Both);
- conn.Close();
- }
- else
- {
- //Start servicing a new connection
- SockClient st = new SockClient(this, conn);
- st.nick = "Guest";
- st.IP = (conn.RemoteEndPoint as IPEndPoint).Address.ToString();
- st.textBuf = new byte[0];
- clients.Add(st);
- //Queue the rest of the job to be executed latter
- //ThreadPool.QueueUserWorkItem(TAcceptConnection, st);
- AcceptConnection_Handler(st);
- }
- //Resume the listening callback loop
- _listener.BeginAccept(ConnectionReady, null);
- }
- catch (ObjectDisposedException ode)
- {
- Console.WriteLine("[" + DateTime.Now.ToString("h:mm:ss") + "] Server Failure: "+ode.ToString());
- try { _listener.Shutdown(SocketShutdown.Both); } catch (Exception e1) { }
- try { _listener.Close(); } catch (Exception e2) { }
- btnConnect.Text = "Start";
- }
- }
- }
- /// <SUMMARY>
- /// Executes OnAcceptConnection method from the service provider.
- /// </SUMMARY>
- private void AcceptConnection_Handler(object state)
- {
- Console.WriteLine("[" + DateTime.Now.ToString("h:mm:ss") + "] AcceptConnection_Handler()");
- SockClient st = state as SockClient;
- try {
- st.OnAcceptConnection();
- }
- catch (Exception e)
- {
- //report error in provider... Probably to the EventLog
- Console.WriteLine("[" + DateTime.Now.ToString("h:mm:ss") + "] ERROR! " + e.ToString());
- }
- }
- public class SockClient
- {
- public Socket socket;
- [NonSerialized]
- public Form1 server;
- public string IP;
- public string nick;
- public Thread ReceiveThread;
- public Stopwatch pingtime;
- public string data;
- public byte[] textBuf;
- PointF curPos;
- public SockClient(Form1 server, Socket socket)
- {
- this.server = server;
- this.socket = socket;
- this.IP = (socket.RemoteEndPoint as IPEndPoint).Address.ToString();
- this.nick = "Unknown";
- pingtime = new Stopwatch();
- data = "";
- Point p;
- GetCursorPos(out p);
- curPos.X = p.X;
- curPos.Y = p.Y;
- }
- public void OnAcceptConnection()
- {
- Console.WriteLine("[" + DateTime.Now.ToString("h:mm:ss") + "] " + IP + " Client connected.");
- StartReadThread();
- }
- public void OnReceiveData()
- {
- String msg = Encoding.ASCII.GetString(textBuf);
- textBuf = new byte[0];
- //Stopwatch stopwatch = new Stopwatch();
- //int c = 0;
- //stopwatch.Start();
- while (msg.Contains("\r\n"))
- {
- String cmd = msg.Substring(0, msg.IndexOf("\r\n"));
- // scrape out command
- msg = msg.Substring(cmd.Length + ("\r\n").Length);
- Handle(cmd);
- //c++;
- }
- //stopwatch.Stop();
- //Console.WriteLine("[" + DateTime.Now.ToString("h:mm:ss") + "] " + IP + " Handled " + c + " msgs in " + (stopwatch.ElapsedMilliseconds) + "ms (" + (stopwatch.ElapsedMilliseconds / c) + "ms per).");
- //textBuf = new byte[0];//Encoding.ASCII.GetBytes(msg);
- }
- public void Handle(String msg)
- {
- String[] args = msg.Split(' ');
- switch (args[0])
- {
- case "MOVE":
- {
- float X = float.Parse(args[1]);
- float Y = float.Parse(args[2]);
- curPos.X += X; curPos.Y += Y;
- Cursor.Position = Point.Round(curPos);
- break;
- }
- case "LCLICK":
- {
- int state = int.Parse(args[2]);
- break;
- }
- case "RCLICK":
- {
- int state = int.Parse(args[2]);
- break;
- }
- default:
- Console.WriteLine("[" + DateTime.Now.ToString("h:mm:ss") + "] " + IP + ":? " + msg);
- break;
- }
- }
- public void OnDropConnection()
- {
- while (ReceiveThread.IsAlive)
- ReceiveThread.Interrupt();
- if (socket.Connected)
- {
- Send("Closing Connection.");
- socket.Shutdown(SocketShutdown.Both);
- socket.Close();
- }
- Console.WriteLine("[" + DateTime.Now.ToString("h:mm:ss") + "] " + IP + " Client dropped.");
- server.EndConnection(this);
- }
- public void LiveCheck()
- {
- if (socket.Connected)
- OnDropConnection();
- }
- public void Send(string msg)
- {
- try
- {
- // Encode the data string into a byte array.
- byte[] buf = Encoding.ASCII.GetBytes(msg + "\r\n");
- // Send the data through the socket.
- int bytesSent = socket.Send(buf);
- Console.WriteLine("[" + DateTime.Now.ToString("h:mm:ss") + "] " + IP + " Client denied access: Busy");
- //AddLog("<Server> -> " + clients[ID].nick + ": " + msg);
- }
- catch (Exception e)
- {
- // remove the list item
- server.EndConnection(this);
- }
- }
- /// <SUMMARY>
- /// Executes OnReceiveData method from the service provider.
- /// </SUMMARY>
- public void StartReadThread()
- {
- ReceiveThread = new Thread(new ThreadStart(() =>
- {
- try
- {
- Console.WriteLine("[" + DateTime.Now.ToString("h:mm:ss") + "] Receiver opened.");
- while (socket.Connected)
- {
- int l = socket.Available;
- if (l > 0)
- {
- Stopwatch counter = new Stopwatch();
- counter.Start();
- //Console.WriteLine("[" + DateTime.Now.ToString("h:mm:ss") + "] Receiver aquired "+l+" bytes.");
- byte[] prev = textBuf;
- byte[] rec = new byte[l];
- // receive all and add to buffer
- socket.Receive(rec);
- textBuf = new byte[prev.Length + rec.Length];
- System.Buffer.BlockCopy(prev, 0, textBuf, 0, prev.Length);
- System.Buffer.BlockCopy(rec, 0, textBuf, prev.Length, rec.Length);
- // handle received info
- try
- {
- try
- {
- // send to handler
- try
- {
- OnReceiveData();
- }
- catch (ObjectDisposedException e)
- {
- Console.WriteLine("[" + DateTime.Now.ToString("h:mm:ss") + "] " + IP + ":" + nick + " Diconnected(Connection Closed)");
- return;
- }
- }
- catch (Exception e)
- {
- Console.WriteLine("[" + DateTime.Now.ToString("h:mm:ss") + "] <" + IP + ":" + nick + "> Error handling data: " + e.ToString());
- }
- }
- catch (Exception e)
- {
- //report error in the provider
- Console.WriteLine("[" + DateTime.Now.ToString("h:mm:ss") + "] <" + IP + ":" + nick + "> Read Error! " + e.ToString());
- }
- Console.WriteLine("[" + DateTime.Now.ToString("h:mm:ss") + "] <" + IP + ":" + nick + "> Parsed " + l + "bytes in " + counter.ElapsedMilliseconds + "ms");
- counter.Stop();
- }
- // sleep a moment and give it another run
- Thread.Sleep(1000/30); // tries 30 times a second
- }
- Console.WriteLine("[" + DateTime.Now.ToString("h:mm:ss") + "] " + IP + ":" + nick + " Disconnected(Client Lost)");
- try
- {
- OnDropConnection();
- }
- catch (ObjectDisposedException ode)
- {
- }
- return;
- }
- catch (ThreadInterruptedException e)
- {
- // trying to kill process
- }
- catch (Exception une)
- {
- Console.WriteLine("[" + DateTime.Now.ToString("h:mm:ss") + "] " + IP + ":" + nick + " Unexpected Reader Error: " + une.ToString());
- }
- try
- {
- OnDropConnection();
- return;
- }
- catch (ObjectDisposedException ode)
- {
- }
- Console.WriteLine("[" + DateTime.Now.ToString("h:mm:ss") + "] " + IP + ":" + nick + " Read thread ended!");
- }));
- ReceiveThread.Start();
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment