Click here to Skip to main content
15,896,727 members
Articles / Programming Languages / C#

RemoteConsole

Rate me:
Please Sign up or sign in to vote.
3.20/5 (2 votes)
27 Aug 2007CPOL2 min read 33K   674   26  
Remote console allows to send commands to a remote computer located on the Internet
namespace RemoteAdminWebService
{
	using System;
	using System.Net;
	using System.Net.Sockets;
	using System.Threading;
	using System.Collections;
	using System.Text;
	
	/// <summary>
	/// Server offer posibility to receive data through sockets
	/// </summary>
	public class Server
	{
		#region Fields

		private int				_Port = 1234;
	
		private IPEndPoint		_ServerEndPoint;
	
		private Socket			_ServerSocket;
	
		private Socket			_ClientSocket;
	
		private CommandFactory	_CmdFactory;

		private Thread			_ServerThread;

		private bool			_ServerStarted;

		private bool			_KeepRunning;

		#endregion

		#region Construction

		public Server(CommandFactory cmdFactory)
		{
			_ServerEndPoint = new IPEndPoint( IPAddress.Any, _Port);
			_ServerSocket	= new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
			_CmdFactory		= cmdFactory;

			_ServerStarted	= false;
			_KeepRunning	= true;
		}

		#endregion

		#region Methods

		public void Start()
		{
			if ( _ServerStarted )
				return;

			_ServerStarted = true;

			_ServerThread = new Thread( new ThreadStart( ServerLoop ) );
			_ServerThread.Start();
		}

		public void Stop()
		{
			_KeepRunning = false;
			_ServerSocket.Close();
		}

		private void ServerLoop()
		{
			try
			{
				_ServerSocket.Bind( _ServerEndPoint );

				_ServerSocket.Listen( 10 );

				while( _KeepRunning )
				{
					_ClientSocket = _ServerSocket.Accept();

					Thread _thread = new Thread( new ThreadStart( ClientLoop ) );
					_thread.IsBackground = true;

					_thread.Start();
				}
			}
			catch(Exception _ex)
			{}
		}

		private void ClientLoop()
		{
			byte[] _data = new byte[1024];

			Socket _socket = _ClientSocket;

			try
			{
				while( _KeepRunning )
				{
					int _lenght = _socket.Receive( _data, 0, 1024, SocketFlags.None);
					if (_lenght > 0)
					{
						string _message = Encoding.ASCII.GetString( _data, 0, _lenght );
						_CmdFactory.ProcessStream( _message );
					}
					else
						Thread.Sleep( 10 );
				}
			}
			catch(Exception _ex)
			{
		
			}
		}

		#endregion
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Romania Romania
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions