[Delivery-boy-cvs] server/DeliveryBoyS/classes clsEasySocket.cs,NONE,1.1 clsEasyTCPServer.cs,NONE,1.
Status: Planning
Brought to you by:
mkloubert
From: Marcel K. <gen...@us...> - 2005-03-05 10:36:28
|
Update of /cvsroot/delivery-boy/server/DeliveryBoyS/classes In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv14590/DeliveryBoyS/classes Added Files: clsEasySocket.cs clsEasyTCPServer.cs Log Message: - Added classes: Global, clsEasySocket and clsEasyTCPServer - Added GPL License & Readme.txt - Added some functions, like menu browsing or starting the server (incl. event) to the MainClass --- NEW FILE: clsEasyTCPServer.cs --- // DeliveryBoy (Client) - FLAC file sharing tool for .NET // http://deliveryboy.sourceforge.net // // // Copyright (C) 2005 Marcel Joachim Kloubert // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // using System; using System.Collections; using System.Net.Sockets; using System.Timers; /*! \class clsEasyTCPServer clsEasyTCPServer.cs "clsEasyTCPServer.cs" * * \brief Easy-to-use TCP Server class. * * This class is a simple TCP server class that uses clsEasySocket * * \author generalpd * * \date 2005-01-30 * * \bug (none) * * \remarks Last changed by: $Author: generalpd $ in revision $Revision: 1.1 $ on $Date: 2005/03/05 10:36:14 $ * * \todo Adding methods for handling data transfer between sockets. * * \note * $Log: clsEasyTCPServer.cs,v $ * Revision 1.1 2005/03/05 10:36:14 generalpd * - Added classes: Global, clsEasySocket and clsEasyTCPServer * - Added GPL License & Readme.txt * - Added some functions, like menu browsing or starting the server (incl. event) to the MainClass * * * */ public class clsEasyTCPServer { /// Timer private Timer m_oTimer = null; /// Listen socket private TcpListener m_oListenSocket = null; /// Local port private Int32 m_i32Port = -1; /// Last occurred exception private Exception m_oLastException = null; /// Listen queue size private Int32 m_i32ListenQueue = -1; /// Maximum connections private UInt32 m_ui32MaxConnections = 0; /// Connections private clsEasySocket[] m_oConnections; /// Accept-Event-Handler-Struct public delegate void AcceptHandler(System.Object sender, System.Net.Sockets.Socket socket); /// Accept-Event-Handler public event AcceptHandler OnAccept; /// Receive-Event-Handler-Struct public delegate void ReceiveHandler(System.Object sender, clsEasySocket socket, System.Byte[] buffer, System.Int32 bytes_read); /// Receive-Event-Handler public event ReceiveHandler OnReceive; /*! \fn public clsEasyTCPServer * \brief Inits all necessary stuff * * \param (none) * * \return (none) */ public clsEasyTCPServer() { //ListenQueue = m_oListenSocket.ListenQueue; MaxConnections = 0; } /*! \property public UInt32 Connections * \brief Returns all availible clsEasySocket connections. * * \param (none) * * \return List of all connections */ public clsEasySocket[] Connections { get { return m_oConnections; } } /*! \property public UInt32 MaxConnections * \brief Returns the size of maximum server connections or sets it. * * \param value New size (0 => unlimited) * * \return Maximum connections (0 => unlimited) */ public UInt32 MaxConnections { get { return m_ui32MaxConnections; } set { int i = 0; m_ui32MaxConnections = value; m_oConnections = new clsEasySocket[m_ui32MaxConnections]; for (i = 0; i < m_oConnections.GetLength(0); i++) m_oConnections[i] = new clsEasySocket(); } } /*! \property public Int32 ListenQueue * \brief Returns the size of the listen queue or sets it. * * \param value New size * * \return Size of listen queue */ public Int32 ListenQueue { get { return m_i32ListenQueue; } set { m_i32ListenQueue = value; } } /*! \fn public Int32 Port * \brief Return or set the port of this server * * \param value New port * * \return Port */ public Int32 Port { get { return m_i32Port; } set { m_i32Port = value; InitListenSocket(); } } /*! \fn public bool Listening * \brief Return if this server is listening * * \param (none) * * \return Is listening (true) or not (false) */ public bool Listening { get { // return m_oListenSocket.Connected; return true; } } /*! \fn public UInt32 Stop () * \brief Stops the server. * * \param (none) * * \return Error code:<BR> * 0 => no error<BR> * 1 => general exception<BR> * 2 => not listening */ public UInt32 Stop () { try { m_oTimer.Stop(); m_oTimer = null; m_oListenSocket.Stop(); return SetLastException(0, null); } catch (Exception e) { return SetLastException(1, e); } } /*! \fn public UInt32 Start () * \brief Starts the server. * * \param (none) * * \return Error code:<BR> * 0 => no error<BR> * 1 => general exception<BR> * 2 => already listening */ public UInt32 Start () { try { // Init listener and start it InitListenSocket(); m_oListenSocket.Start(); // init timer and start it m_oTimer = new Timer(125); m_oTimer.Elapsed += new ElapsedEventHandler(this.TimerElapsed); m_oTimer.Start(); return SetLastException(0, null); } catch (Exception e) { return SetLastException(1, e); } } /*! \property public Exception LastException * \brief Returns the last occurred exception. * * \param (none) * * \return Exception object (null => no error) */ public Exception LastException { get { return m_oLastException; } } /*! \fn private UInt32 SetLastException (UInt32 ui32_ErrorCode, Exception oNewException) * \brief Sets the last occurred exception. * * \param ui32_ErrorCode Error code. * \param oNewException The new exception object. * * \return Error code submitted by ui32_ErrorCode */ private UInt32 SetLastException (UInt32 ui32_ErrorCode, Exception oNewException) { m_oLastException = oNewException; return ui32_ErrorCode; } /*! \fn private void InitListenSocket () * \brief Inits the listening socket with all stuff * * \param (none) * * \return (none) */ private void InitListenSocket () { m_oListenSocket = new TcpListener(Port); return; } /*! \fn private void TimerElapsed (object sender, ElapsedEventArgs e); * \brief Timer elapsed * * \param sender This timer instance * \param ElapsedEventArgs Arguments * * \return (none) */ private void TimerElapsed (object sender, ElapsedEventArgs e) { if (m_oListenSocket.Pending()) { int i = 0; bool boolIsFull = true; Socket s = m_oListenSocket.AcceptSocket(); if (null != OnAccept) OnAccept(this, s); if (s.Connected) { for (i = 0; i < m_oConnections.GetLength(0); i++) { if (!m_oConnections[i].Connected) { m_oConnections[i] = new clsEasySocket(s); m_oConnections[i].OnReceive += new clsEasySocket.ReceiveHandler(ReceiveData); boolIsFull = false; break; } } if (boolIsFull) s.Close(); } } return; } /*! \fn private void ReceiveData (System.Object sender, System.Byte[] buffer, System.Int32 bytes_read); * \brief Data ready for read * * \param sender This timer instance * \param buffer Data * \param bytes_read # of bytes that are ready for reading * * \return (none) */ private void ReceiveData (System.Object sender, System.Byte[] buffer, System.Int32 bytes_read) { if (null != OnReceive) OnReceive(this, (clsEasySocket)sender, buffer, bytes_read); return; } } --- NEW FILE: clsEasySocket.cs --- // DeliveryBoy (Client) - FLAC file sharing tool for .NET // http://deliveryboy.sourceforge.net // // // Copyright (C) 2005 Marcel Joachim Kloubert // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // using System; using System.Net; using System.Net.Sockets; using System.Text; /*! \class clsEasySocket clsEasySocket.cs "clsEasySocket.cs" * * \brief Easy-to-use socket class. * * This class is a simple version of the System.Net.Socket.Socket-Class * * \author generalpd * * \date 2005-01-30 * * \bug (none) * * \remarks Last changed by: $Author: generalpd $ in revision $Revision: 1.1 $ on $Date: 2005/03/05 10:36:14 $ * * \todo Adding methods for handling data transfer between sockets. * * \note * $Log: clsEasySocket.cs,v $ * Revision 1.1 2005/03/05 10:36:14 generalpd * - Added classes: Global, clsEasySocket and clsEasyTCPServer * - Added GPL License & Readme.txt * - Added some functions, like menu browsing or starting the server (incl. event) to the MainClass * * * */ public class clsEasySocket { /// Default buffer size in byte private const Int32 DEFAULT_BUFFER_SIZE = 1024; /// Default listen queue size private const Int32 DEFAULT_LISTENQUEUE_SIZE = 16; /// Byte buffer private byte[] b_Buffer; /// Last occurred exception private Exception m_oLastException = null; /// For ASCII conversion private ASCIIEncoding m_oASCII = null; /// Socket private Socket m_oSocket = null; /// Local port private Int32 m_i32LocalPort = 0; /// Remote address private string m_strRemoteAddr = "0.0.0.0"; /// Remote port private Int32 m_i32RemotePort = 0; /// Remote end point private IPEndPoint m_RemoteEndPoint = null; /// Listen queue private Int32 m_i32ListenQueue = -1; /// Listen queue private Int32 m_i32BufferSize = 0; /// Auto accept? private bool m_boolAutoAccept = true; /// Use this address type private const AddressFamily c_AddressFamily = AddressFamily.InterNetwork; /// Use this socket type private const SocketType c_SocketType = SocketType.Stream; /// Use this protocol type private const ProtocolType c_ProtocolType = ProtocolType.Tcp; /// Accept-Event-Handler-Struct public delegate void AcceptHandler(System.Object sender, System.Net.Sockets.Socket socket); /// Accept-Event-Handler public event AcceptHandler OnAccept; /// Connect-Event-Handler-Struct public delegate void ConnectHandler(System.Object sender, System.Net.Sockets.Socket socket); /// Connect-Event-Handler public event ConnectHandler OnConnect; public event ConnectHandler OnConnectWithRemote; /// Error-Event-Handler-Struct public delegate void ErrorHandler(System.Object sender, System.Exception e); /// Error-Event-Handler public event ErrorHandler OnError; /// Receive-Event-Handler-Struct public delegate void ReceiveHandler(System.Object sender, System.Byte[] buffer, System.Int32 bytes_read); /// Receive-Event-Handler public event ReceiveHandler OnReceive; /*! \fn clsEasySocket * \brief Inits all necessary stuff * * \param (none) * * \return (none) */ public clsEasySocket() { m_oSocket = new Socket(c_AddressFamily, c_SocketType, c_ProtocolType); InitRest(); } /*! \fn clsEasySocket * \brief Inits all necessary stuff * * \param socket * * \return (none) */ public clsEasySocket(Socket socket) { m_oSocket = socket; InitRest(); if (m_oSocket.Connected) m_oSocket.BeginReceive(b_Buffer, 0, BufferSize, SocketFlags.None, new AsyncCallback(this.pOnReceive), m_oSocket); } /*! \fn private void InitRest () * \brief Inits the rest * * \param (none) * * \return (none) */ private void InitRest () { // initialize all necessary vars m_oASCII = new ASCIIEncoding(); RemoteAddress = "0.0.0.0"; RemotePort = 0; ListenQueue = DEFAULT_LISTENQUEUE_SIZE; BufferSize = DEFAULT_BUFFER_SIZE; AutoAccept = true; SocketObject.Blocking = false; b_Buffer = new byte[BufferSize]; SetLastException(0, null); } /*! \property public string RemoteAddress * * \brief Returns the remote address or sets it. * * \param value New remote address * * \return Remote address */ public string RemoteAddress { get { return m_strRemoteAddr; } set { try { m_RemoteEndPoint = GetEndPoint(value.Trim(), RemotePort); m_strRemoteAddr = value.Trim(); SetLastException(0, null); } catch (Exception e) { SetLastException(1, e); } } } /*! \property public Int32 ListenQueue * \brief Returns the size of the listen queue or sets it. * * \param value New size * * \return Size of listen queue */ public Int32 ListenQueue { get { return m_i32ListenQueue; } set { m_i32ListenQueue = value; } } /*! \property public Int32 BufferSize * \brief Returns the socket buffer size in bytes or sets it. * * \param value New size * * \return Size of buffer, in byte */ public Int32 BufferSize { get { return m_i32BufferSize; } set { m_i32BufferSize = value; } } /*! \property public Int32 RemotePort * \brief Returns the remote port or sets it. * * \param value New remote port * * \return Remote port */ public Int32 RemotePort { get { return m_i32RemotePort; } set { try { m_RemoteEndPoint = GetEndPoint(RemoteAddress, value); m_i32RemotePort = value; SetLastException(0, null); } catch (Exception e) { SetLastException(1, e); } } } /*! \property public Socket SocketObject * \brief Returns the socket object. * * \param (none) * * \return Socket object */ public System.Net.Sockets.Socket SocketObject { get { return m_oSocket; } } /*! \property public Int32 LocalPort * \brief Returns the local port or sets it. * * \param value New local port * * \return Local port */ public Int32 LocalPort { get { return m_i32LocalPort; } set { m_i32LocalPort = value; } } /*! \property public bool Connected * \brief Returns if this socket is connected or not. * * \param (none) * * \return Is connected (TRUE) or not (FALSE) */ public bool Connected { get { return m_oSocket.Connected; } } /*! \property public Exception LastException * \brief Returns the last occurred exception. * * \param (none) * * \return Exception object (null => no error) */ public Exception LastException { get { return m_oLastException; } } /*! \fn private UInt32 SetLastException (UInt32 ui32_ErrorCode, Exception oNewException) * \brief Sets the last occurred exception. * * \param ui32_ErrorCode Error code. * \param oNewException The new exception object. * * \return Error code submitted by ui32_ErrorCode */ private UInt32 SetLastException (UInt32 ui32_ErrorCode, Exception oNewException) { m_oLastException = oNewException; return ui32_ErrorCode; } /*! \fn public UInt32 Connect() * \brief Connects to RemoteAddress:RemotePort. * * \param (none) * * \return Error code:<BR> * 0 => no error<BR> * 1 => general exception<br> * 2 => already connected */ public UInt32 Connect() { try { if (!Connected) { SocketObject.BeginConnect(m_RemoteEndPoint, new AsyncCallback(this.pOnConnectWithRemote), SocketObject); return SetLastException(0, null); } else return SetLastException(2, null); } catch (Exception e) { return SetLastException(1, e); } } /*! \fn public UInt32 SocketObject() * \brief Disconnects or close socket. * * \param (none) * * \return Error code:<BR> * 0 => no error<BR> * 1 => general exception<br> * 2 => not connected */ public UInt32 Close() { try { if (!Connected) return SetLastException(2, null); else { SocketObject.Shutdown(SocketShutdown.Both); SocketObject.Close(); return SetLastException(0, null); } } catch (Exception e) { return SetLastException(1, e); } } /*! \fn public bool AutoAccept * \brief Accept each connection request or first run OnAccept-event. * * \param value New state:<BR> * TRUE => Accept each connection request<BR> * FALSE => First run OnAccept event * * \return State:<BR> * TRUE => Accept each connection request<BR> * FALSE => First run OnAccept event */ public bool AutoAccept { get { return m_boolAutoAccept; } set { m_boolAutoAccept = value; } } /*! \fn private IPEndPoint GetEndPoint (string str_Address, Int32 i32_Port) * \brief Creates an end point by an ip address and a port * * \param string str_Address * \param i32_Port Port * * \return End point ... or null if an exception occurred */ private IPEndPoint GetEndPoint (string str_Address, Int32 i32_Port) { try { // create end point IPAddress oIPAddress = Dns.Resolve(str_Address.Trim()).AddressList[0]; IPEndPoint oIPEndPoint = new IPEndPoint(oIPAddress, i32_Port); SetLastException(0, null); return oIPEndPoint; } catch (Exception e) { SetLastException(1, e); return null; } } /*! \fn public UInt32 SendString(string str_Expression) * \brief Sends a string to the remote host. * * \param str_Expression The string that should be send * * \return Error code:<BR> * 0 => no error<BR> * 1 => general exception<BR> * 2 => not connected */ public UInt32 SendString(string str_Expression) { try { byte[] bBuffer = m_oASCII.GetBytes(str_Expression); return SetLastException(Send(bBuffer), LastException); } catch (Exception e) { return SetLastException(1, e); } } /*! \fn public UInt32 Send(byte[] b_Bytes) * \brief Sends a couple of bytes to the remote host. * * \param b_Bytes Array of bytes * * \return Error code:<BR> * 0 => no error<BR> * 1 => general exception<BR> * 2 => not connected */ public UInt32 Send(byte[] b_Bytes) { try { if (Connected) { SocketObject.Send(b_Bytes); return SetLastException(0, null); } else // Not connected return SetLastException(2, null); } catch (Exception e) { return SetLastException(1, e); } } /*! \fn public UInt32 Listen() * \brief Listen from for connections from LocalAddress:LocalPort. * * \param (none) * * \return Error code:<BR> * 0 => no error<BR> * 1 => general exception<br> * 2 => already connected */ public UInt32 Listen() { try { if (!Connected) { SocketObject.Bind( new IPEndPoint(IPAddress.Any, LocalPort)); SocketObject.Listen(ListenQueue); SocketObject.BeginAccept( new AsyncCallback(this.pOnConnectRequest), SocketObject); return SetLastException(0, null); } else return SetLastException(2, null); } catch (Exception e) { return SetLastException(1, e); } } /*! \fn private void pOnConnectRequest ( IAsyncResult ar ) * \brief Is invoked if a remote socket wants to connect * * \param ar Async result * * \return (none) */ private void pOnConnectRequest ( IAsyncResult ar ) { try { if (AutoAccept) { m_oSocket = SocketObject.EndAccept(ar); if (null != OnConnect) this.OnConnect(this, m_oSocket); m_oSocket.BeginReceive(b_Buffer, 0, BufferSize, SocketFlags.None, new AsyncCallback(this.pOnReceive), m_oSocket); } else { if (null != OnAccept) this.OnAccept(this, m_oSocket); } } catch (Exception e) { pOnError(e); } return; } /*! \fn private void pOnReceive ( IAsyncResult ar ) * \brief Is invoked if a remote socket has sended data to this socket * * \param ar Async result * * \return (none) */ private void pOnReceive ( IAsyncResult ar ) { try { int iBytesRead = SocketObject.EndReceive(ar); if (null != OnReceive) this.OnReceive(this, b_Buffer, iBytesRead); // b_Buffer = new byte[BufferSize]; m_oSocket.BeginReceive(b_Buffer, 0, BufferSize, SocketFlags.None, new AsyncCallback(this.pOnReceive), m_oSocket); } catch (Exception e) { pOnError(e); } return; } /*! \fn private void pOnError ( Exception e ) * \brief Is invoked if an error occurred * * \param ar Async result * * \return (none) */ private void pOnError ( Exception e ) { if (null != OnError) this.OnError(this, e); return; } /*! \fn private void pOnConnectWithRemote ( IAsyncResult ar ) * \brief Is invoked if an connection with a remote established * * \param ar Async result * * \return (none) */ private void pOnConnectWithRemote ( IAsyncResult ar ) { SocketObject.EndConnect(ar); if (null != OnConnectWithRemote) this.OnConnectWithRemote(this, m_oSocket); return; } } |