clsTCPServer.cs

00001 // C# ClassLib
00002 // http://csharp-classlib.sourceforge.net
00003 //
00004 //
00005 // Copyright (C) 2005 Marcel Joachim Kloubert
00006 // 
00007 // This program is free software; you can redistribute it and/or
00008 // modify it under the terms of the GNU General Public License
00009 // as published by the Free Software Foundation; either version 2
00010 // of the License, or (at your option) any later version.
00011 // 
00012 // This program is distributed in the hope that it will be useful,
00013 // but WITHOUT ANY WARRANTY; without even the implied warranty of
00014 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00015 // GNU General Public License for more details.
00016 // 
00017 // You should have received a copy of the GNU General Public License
00018 // along with this program; if not, write to the Free Software
00019 // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
00020 //
00021 
00022 using System;
00023 using System.Collections;
00024 using System.Net.Sockets;
00025 using System.Timers;
00026 
00027 namespace CSharp_ClassLib.Net
00028 {
00056         public class TCPServer : System.Object
00057         {
00059                 private System.Net.Sockets.TcpListener m_oTCPListener;
00061                 private System.Int32 m_iMaximumConnections;
00063                 private System.UInt16 m_iPort;
00065                 private System.Net.Sockets.Socket[] m_oConnections;
00067                 private System.Int32 m_iBufferSize;
00068                 
00069                 // timer that checks for connections attempts
00070                 private System.Timers.Timer m_oTimer;
00071                 
00072                 // Socket buffers
00073                 private System.Collections.ArrayList m_oSocketBuffers;
00074         
00076         public delegate void AcceptHandler(System.Object sender, System.Net.Sockets.Socket socket);
00078         public event AcceptHandler OnAccept;
00080         public delegate void DisconnectHandler(System.Object sender, System.Net.Sockets.Socket socket);
00082         public event DisconnectHandler OnDisconnect;
00084         public delegate void ErrorHandler(System.Object sender, System.Exception e);
00086         public event ErrorHandler OnError;
00088         public delegate void ReceiveHandler(System.Object sender, System.Net.Sockets.Socket socket, System.Byte[] buffer);
00090         public event ReceiveHandler OnReceive;
00091                 
00092                 
00097         public TCPServer()
00098                 {
00099                 this.m_oSocketBuffers = new System.Collections.ArrayList();
00100                 this.MaxConnections = 10;
00101                 this.Port = 23;
00102                 this.BufferSize = 2050;
00103                 this.m_oTimer = null;
00104                 
00105                 return;
00106                 }
00107         
00116         public System.Int32 BufferSize
00117         {
00118                 get { return this.m_iBufferSize; }
00119                 
00120                 set { this.m_iBufferSize = value; }
00121         }
00122         
00131         public System.Int32 MaxConnections
00132         {
00133                 get { return this.m_iMaximumConnections; }
00134                 
00135                 set
00136                 {
00137                         System.Int32 i = 0;
00138                         
00139                         if (value <= 0)
00140                                 // we need more than 0 max. connections!
00141                                 throw ( new System.ArgumentException(" Invalid number of maximum connections! ", "") );
00142                         
00143                         this.m_iMaximumConnections = value;
00144                         this.m_oConnections = new System.Net.Sockets.Socket[this.m_iMaximumConnections];
00145                         
00146                         this.m_oSocketBuffers = new System.Collections.ArrayList();
00147                         for (i = 0; i < this.m_oConnections.GetLength(0); i++)
00148                         {
00149                                  this.m_oConnections[i] = null;
00150                                  this.m_oSocketBuffers.Add( new System.Byte[this.BufferSize] );
00151                         }
00152                 }
00153         }
00154         
00163         public System.UInt16 Port
00164         {
00165                 get { return this.m_iPort; }
00166                 set { this.m_iPort = value; }
00167         }
00168         
00175         public System.Net.Sockets.Socket[] Connections
00176         {
00177                 get { return m_oConnections; }
00178         }
00179         
00184         public void Start ()
00185         {
00186                 try
00187                 {                                               
00188                         this.InitListenSocket();
00189                         this.m_oTCPListener.Start();
00190                         
00191                         // init timer that checks if connections are pending
00192                         this.m_oTimer = new System.Timers.Timer(125);
00193                         this.m_oTimer.Elapsed += new System.Timers.ElapsedEventHandler(this.m_oTimer_Elapsed);
00194                         this.m_oTimer.Enabled = true;
00195                 }
00196                 catch (System.Exception e)
00197                 {
00198                         this.pOnError(e, null);
00199                 }
00200         }
00201         
00206         public void Stop ()
00207         {
00208                 try
00209                 {                                                                       
00210                         this.m_oTCPListener.Stop();
00211                 }
00212                 catch (System.Exception e)
00213                 {
00214                         this.pOnError(e, null);
00215                 }
00216         }
00217         
00225         private void pOnError (System.Exception e, System.Net.Sockets.Socket socket)
00226         {
00227                 if ("system.net.sockets.socketexception" == e.GetType().FullName.Trim().ToLower())
00228                 {
00229                         if (
00230                             (10053 == ((System.Net.Sockets.SocketException)e).ErrorCode) ||
00231                             (10054 == ((System.Net.Sockets.SocketException)e).ErrorCode)
00232                            )
00233                         {
00234                                 // remote closed connection                                     
00235                                         this.pOnDisconnect(socket);
00236                                         
00237                                 return;
00238                         }
00239                 }
00240                         
00241                         if (null != this.OnError)
00242                         this.OnError(this, e);
00243                 else
00244                         throw (e);
00245         }
00246                 
00251                 private void InitListenSocket ()
00252                 {
00253                 this.m_oTCPListener = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Any, this.Port);      
00254                 }
00255         
00263                 private void m_oTimer_Elapsed (System.Object sender, System.Timers.ElapsedEventArgs e)
00264                 {
00265                         System.Net.Sockets.Socket s = null;
00266                         
00267                         try
00268                         {
00269                                 if (this.m_oTCPListener.Pending())
00270                                 {
00271                                         // wating connections
00272                                         
00273                                         System.Int32 i = 0;
00274                                         s = this.m_oTCPListener.AcceptSocket();
00275                                         System.Boolean boolFoundFreeSocket = false;
00276                                                                 
00277                                         this.ClearConnections();
00278                                         // search for free socket
00279                                         for (i = 0; i < this.Connections.GetLength(0); i++)
00280                                         {       
00281                                                 if (null == this.Connections[i])
00282                                                 {                                                       
00283                                                         // found free socket
00284 
00285                                                         if (null != this.OnAccept)
00286                                                                 // invoke the event
00287                                                         this.OnAccept(this, s);
00288                                         
00289                                                         if (s.Connected)                                        
00290                                                         {
00291                                                                 this.Connections[i] = s;                                                        
00292                                                                 this.Connections[i].BeginReceive((System.Byte[])m_oSocketBuffers[i], 0, this.BufferSize, System.Net.Sockets.SocketFlags.None, new System.AsyncCallback(this.pOnReceive), this.Connections[i]);
00293                                                         }
00294                                                         
00295                                                         boolFoundFreeSocket = true;                                             
00296                                                         break;
00297                                                 }
00298                                         }
00299                                         
00300                                         if (!boolFoundFreeSocket)
00301                                                 // no more connections!
00302                                                 s.Close();
00303                                 }
00304                         }
00305                         catch (System.Exception e2)
00306                         {
00307                                 this.pOnError(e2, s);
00308                         }
00309                         
00310                 return;
00311                 }
00312                 
00317                 private void ClearConnections ()
00318                 {
00319                         System.Int32 i = 0;
00320                         
00321                         for (i = 0; i < this.Connections.GetLength(0); i++)
00322                         {
00323                                 if (null != this.Connections[i])
00324                                 {
00325                                         if (!this.Connections[i].Connected)
00326                                                 this.Connections[i] = null;
00327                                 }
00328                         }
00329                 }
00330                 
00337                 private void pOnReceive ( System.IAsyncResult ar )
00338                 {
00339                         try
00340                         {
00341                                 System.Int32 i = 0;
00342                                 System.Int32 iBytesRead = 0;
00343                                 System.Byte[] bBuffer = new System.Byte[0];
00344                         
00345                                 for (i = 0; i < this.Connections.GetLength(0); i++)
00346                                 {
00347                                         if ( this.Connections[i].Equals(ar.AsyncState) )
00348                                         {
00349                                                 // receive data
00350                                                 iBytesRead = this.Connections[i].EndReceive(ar);                                        
00351                                                 if (iBytesRead > 0)
00352                                                 {
00353                                                         bBuffer = new System.Byte[iBytesRead];
00354                                                         System.Array.Copy((System.Byte[])m_oSocketBuffers[i], bBuffer, bBuffer.GetLength(0));
00355                                                         
00356                                                         if (null != this.OnReceive)
00357                                                                 // invoke event
00358                                                                 this.OnReceive(this, this.Connections[i], bBuffer);
00359                                                 }
00360                                         
00361                                                 if (null != this.Connections[i])
00362                                                 {
00363                                                         if (this.Connections[i].Connected)
00364                                                                 // is still connected => list for data
00365                                                                 this.Connections[i].BeginReceive((System.Byte[])m_oSocketBuffers[i], 0, this.BufferSize, System.Net.Sockets.SocketFlags.None, new System.AsyncCallback(this.pOnReceive), this.Connections[i]);
00366                                                         else
00367                                                                 this.pOnDisconnect(this.Connections[i]);
00368                                                 }
00369                                                 else
00370                                                         this.pOnDisconnect(this.Connections[i]);
00371                                         
00372                                                 break;
00373                                         }
00374                                 }
00375                         }
00376                         catch (System.Exception e)
00377                         {
00378                                 this.pOnError(e, (System.Net.Sockets.Socket)ar.AsyncState);
00379                         }               
00380                         
00381                         return;
00382                 }
00383                 
00390                 private void pOnDisconnect( System.Net.Sockets.Socket socket )
00391                 {
00392                         if (null != this.OnDisconnect)
00393                                 // invoke the event(s)
00394                                 this.OnDisconnect(this, socket);
00395                         
00396                         this.ClearConnections();
00397                         
00398                         return;
00399                 }
00400         }
00401 }

Generated on Thu Jun 2 08:41:49 2005 for C# ClassLib by  doxygen 1.4.1