|
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.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.