473,657 Members | 2,801 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Socket not receiving data

Airslash
221 New Member
Hello,

The problem is that my server is not receiving data.
The code below are the various classes I designed around sockets. It will be big...

I have run the code with the debugger, and I see in the debug output that the client connects to the server, the events get fired and the disconnect event gets fired as well.

I get confirmation that the data is beeing sent from the client as well, because the function returns a value greater then 0, so the send operation succeeded. The server however never receives the data.

I will not post the interfaces, only the concrete code. I'll add a bit of explanation to each class where possible. I have the feeling that I forgot something somewhere, but I cannot pinpoint it. I'm hoping someone can throw a look at it and pinpoint it for me.
The code should compile if you remove the Interface classes, in case someone wants to test it himself.

1. The server code
Expand|Select|Wrap|Line Numbers
  1. namespace VTServer.IO
  2. {
  3.     public class TCPServer : IServer
  4.     {
  5.         #region Constructor
  6.  
  7.         /// <summary>
  8.         /// Creates a new instance of the TCPServer class and initializes the internal datamembers
  9.         /// with the values of the supplied parameters.
  10.         /// </summary>
  11.         /// <param name="yarn">The yarn that will process and keep track of all the clients.</param>
  12.         /// <param name="port">The port to use for the TCPServer to listen on.</param>
  13.         /// <param name="maximumconnections">The maximum amount of connections allowed.</param>
  14.         public TCPServer(Yarn yarn, int port, int maximumconnections)
  15.         {
  16.             Yarn = yarn;
  17.             MaximumConnections = maximumconnections;
  18.             Interval = 10;
  19.             Port = port;
  20.         }
  21.  
  22.         #endregion
  23.  
  24.         #region Public Properties
  25.  
  26.         /// <summary>
  27.         /// Gets or sets the Yarn that holds all the IFibers beeing handled by the server.
  28.         /// </summary>
  29.         public Yarn Yarn
  30.         {
  31.             get { lock (m_lock_yarn) { return m_yarn; } }
  32.             set { lock (m_lock_yarn) { m_yarn = value; } }
  33.         }
  34.  
  35.         /// <summary>
  36.         /// Gets or sets the maximum amount of connections supported by the server.
  37.         /// </summary>
  38.         public int MaximumConnections
  39.         {
  40.             get { return m_maxconnections; }
  41.             set { m_maxconnections = value; }
  42.         }
  43.  
  44.         /// <summary>
  45.         /// Gets or sets the port used by the TCPServer to listen on for incoming connections.
  46.         /// </summary>
  47.         public int Port
  48.         {
  49.             get { return m_port; }
  50.             set { m_port = value; }
  51.         }
  52.  
  53.         /// <summary>
  54.         /// Gets or sets the interval in ms to wait between subsequent listen routines.
  55.         /// </summary>
  56.         public int Interval
  57.         {
  58.             get { return m_interval; }
  59.             set { m_interval = value; }
  60.         }
  61.  
  62.         /// <summary>
  63.         /// Gets or sets a value indicating if the TCPServer is listening for connections.
  64.         /// </summary>
  65.         public bool Running
  66.         {
  67.             get { return m_running; }
  68.             set { m_running = value; }
  69.         }
  70.  
  71.         #endregion
  72.  
  73.         #region Events
  74.  
  75.         /// <summary>
  76.         /// This event gets fired when the server has accepted a client connection.
  77.         /// </summary>
  78.         public event EventHandler OnClientConnected
  79.         {
  80.             add { lock (m_lock_event) { m_event_connected += value; } }
  81.             remove { lock (m_lock_event) { m_event_connected -= value; } }
  82.         }
  83.  
  84.         /// <summary>
  85.         /// This event gets fired when the client disconnects from the server.
  86.         /// </summary>
  87.         public event EventHandler OnClientDisconnected
  88.         {
  89.             add { lock (m_lock_event) { m_event_disconnected += value; } }
  90.             remove { lock (m_lock_event) { m_event_disconnected -= value; } }
  91.         }
  92.  
  93.         /// <summary>
  94.         /// This event gets fired when a client sends data to the server.
  95.         /// </summary>
  96.         public event EventHandler<ClientDataEventArgs> OnClientData
  97.         {
  98.             add { lock (m_lock_event) { m_event_data += value; } }
  99.             remove { lock (m_lock_event) { m_event_data -= value; } }
  100.         }
  101.  
  102.         /// <summary>
  103.         /// This event gets fired when an error occurs in the server.
  104.         /// This event will be fired asynchronously from the executing code.
  105.         /// </summary>
  106.         public event EventHandler<ErrorEventArgs> OnError
  107.         {
  108.             add { lock (m_lock_event) { m_event_error += value; } }
  109.             remove { lock (m_lock_event) { m_event_error -= value; } }
  110.         }
  111.  
  112.         #endregion
  113.  
  114.         #region Public Methods
  115.  
  116.         /// <summary>
  117.         /// Disposes of the TCPServer and all the internal resources.
  118.         /// </summary>
  119.         public void Dispose()
  120.         {
  121.             // Clean ourselves
  122.             Dispose(true);
  123.  
  124.             // Supress the GC
  125.             GC.SuppressFinalize(this);
  126.         }
  127.  
  128.         /// <summary>
  129.         /// Starts the TCPServer to listen on the specified port with the interval for incoming connections
  130.         /// over the socket.
  131.         /// </summary>
  132.         /// <returns>True if the server has been started on the socket; otherwise false.</returns>
  133.         public bool StartListening()
  134.         {
  135.             if (!Running)
  136.             {
  137.                 // Surround the entire Start routine with a try-catch block to prevent errors from
  138.                 // breaking the code.
  139.                 try
  140.                 {
  141.                     // The first step is to start the internal socket of the server component and listen
  142.                     // for incoming connections.
  143.                     m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  144.                     m_socket.Bind(new IPEndPoint(IPAddress.Any, Port));
  145.                     m_socket.Listen(MaximumConnections);
  146.  
  147.                     // Now that the server is listening for incoming connections, we can start the
  148.                     // internal timer to process the incoming connections.
  149.                     m_timer_listen = new Timer(new TimerCallback(Listen), null, 0, Interval);
  150.  
  151.                     // Now that everything is up and running, we can return true.
  152.                     Running = true;
  153.                     return true;
  154.                 }
  155.                 catch (ApplicationException ex)
  156.                 {
  157.                     // A problem occured while starting the server. Raise the onErrorevent if possible and 
  158.                     // return false since the server could not be started as requested.
  159.                     RaiseOnErrorEvent(ex);
  160.                     return false;
  161.                 }
  162.             }
  163.  
  164.             // Return true here cause the server is running.
  165.             return true;
  166.         }
  167.  
  168.         /// <summary>
  169.         /// Stops the server from listening on the socket.
  170.         /// </summary>
  171.         /// <returns>True if the socket has been successfully close; otherwise false.</returns>
  172.         public bool StopListening()
  173.         {
  174.             lock (m_lock_listensocket)
  175.             {
  176.                 if (Running)
  177.                 {
  178.                     // Surround the entire Stop routine with a try-catch block to prevent errors
  179.                     // from breaking the code.
  180.                     try
  181.                     {
  182.                         // First we stop the timer from executing. That way no additional requests
  183.                         // can/wil be processed.
  184.                         if (m_timer_listen != null)
  185.                             m_timer_listen.Dispose();
  186.  
  187.                         // Now that the timer is no longer active, we can close the socket and stop 
  188.                         // listening on it.
  189.                         m_socket.Close();
  190.  
  191.                         // Return true since we succeeded in stopping the server.
  192.                         Running = false;
  193.                         return true;
  194.                     }
  195.                     catch (ApplicationException ex)
  196.                     {
  197.                         // A problem occured while trying to stop the server. Raise the OnErrorEvent if possible
  198.                         // and return false since the server could not be properly stopped.
  199.                         RaiseOnErrorEvent(ex);
  200.                         return false;
  201.                     }
  202.                 }
  203.  
  204.                 // Return true here cause the server was not running.
  205.                 return true;
  206.             }
  207.         }
  208.  
  209.         #endregion
  210.  
  211.         #region Private Methods
  212.  
  213.         protected void Dispose(bool disposeManagedResources)
  214.         {
  215.             // Check if we're already disposed of. No need to do anything
  216.             // if we're already disposed.
  217.             if (!m_disposed)
  218.             {
  219.                 // Check if we need to dispose of the managed resouces of our class.
  220.                 if (disposeManagedResources)
  221.                 {
  222.                     // First dispose of the internal timer.
  223.                     if (m_timer_listen != null)
  224.                         m_timer_listen.Dispose();
  225.  
  226.                     // Unsubscribe all our eventhandlers.
  227.                     OnClientConnected -= m_event_connected;
  228.                     OnClientDisconnected -= m_event_disconnected;
  229.                     OnClientData -= m_event_data;
  230.                     OnError -= m_event_error;
  231.  
  232.                     // Dispose of the Yarn.
  233.                     m_yarn.Dispose();
  234.  
  235.                     // Close the socket.
  236.                     StopListening();                 
  237.                 }
  238.  
  239.                 // Dispose all the unmanaged resources here.
  240.             }
  241.  
  242.             // Set the disposed flag to true.
  243.             m_disposed = true;
  244.         }
  245.  
  246.         /// <summary>
  247.         /// Listens for incoming connections on the server socket.
  248.         /// When a connection is available, the server will create a new
  249.         /// processing fiber for this socket and keep track of it through the
  250.         /// internal list.
  251.         /// This function is non-blocking and will be called periodicly from an
  252.         /// internal timer on a seperate thread.
  253.         /// </summary>
  254.         /// <param name="state">The state of the timer calling the function. In this case null.</param>
  255.         virtual protected void Listen(object state)
  256.         { 
  257.             // Try to obtain the lock on the listenlock so we have 
  258.             // exclusive access to the socket. If the lock cannot
  259.             // be obtained, simply fall through the function and 
  260.             // wait till the next call.
  261.             if (Monitor.TryEnter(m_lock_listensocket))
  262.             {
  263.                 // Use a try-finally statement to catch errors and always release the lock.
  264.                 try
  265.                 {
  266.                     // Check if there is a connection pending on our socket. If there
  267.                     // is a connection pending, accept the socket. If there are no
  268.                     // connections pending, simply fall through the function and wait
  269.                     // till the next call.
  270.                     if (m_socket.Poll(0, SelectMode.SelectRead))
  271.                     {
  272.                         // There is a connection pending, so accept the connection.
  273.                         // Create a new Fiber based upon the socket.
  274.                         IFiber f = new Fiber(new TCPClient(m_socket.Accept()));
  275.  
  276.                         // Raise the onClientConnected event if possible.
  277.                         RaiseOnClientConnectedEvent(f.Client);
  278.  
  279.                         // Check if the client is still connected. If the client is no longer
  280.                         // connected to the server, raise the on Disconnect event and exit
  281.                         // the function.
  282.                         if (!f.Client.Connected)
  283.                         {
  284.                             // No longer connected, so raise the onDisconnect event if possible.
  285.                             RaiseOnClientDisconnectedEvent(f.Client);
  286.  
  287.                             // Get rid of the fiber we created.
  288.                             f.Dispose();
  289.  
  290.                             // Exit the function.
  291.                             return;
  292.                         }
  293.  
  294.                         // Configure the fiber to take over the events we require.
  295.                         f.OnData += m_event_data;
  296.  
  297.                         // Add the fiber to the Yarn of fibers.
  298.                         Yarn.Add(f);
  299.  
  300.                         // Start the fiber
  301.                         f.Start(0, 10);
  302.                     }
  303.                 }
  304.                 catch(ApplicationException ex)
  305.                 {
  306.                     // Raise the onError event if possible.
  307.                     RaiseOnErrorEvent(ex);
  308.                 }
  309.                 finally
  310.                 {
  311.                     // Release the lock we just acquired.
  312.                     Monitor.Exit(m_lock_listensocket);
  313.                 }
  314.             }
  315.         }
  316.  
  317.         /// <summary>
  318.         /// Raises the OnError event asynchronously if there are subscribers to the event.
  319.         /// If there are no subscribers to the event, the call is ignored.
  320.         /// </summary>
  321.         /// <param name="ex">The exception that has been raised.</param>
  322.         virtual protected void RaiseOnErrorEvent(ApplicationException ex)
  323.         {
  324.             // Obtain the lock to the events so we have exclusive access
  325.             // to the event handler.
  326.             lock (m_lock_event)
  327.             {
  328.                 // Copy the event handler to a local variable to prevent racing conditions
  329.                 // from breaking the code.
  330.                 EventHandler<ErrorEventArgs> handler = m_event_error;
  331.  
  332.                 // Check if there are sufficient subscribers.
  333.                 if (handler != null)
  334.                     handler.BeginInvoke(this, new ErrorEventArgs(ex), new AsyncCallback(CleanCallBack), null);
  335.             }
  336.         }
  337.  
  338.         /// <summary>
  339.         /// Raises the OnClientConnected event synchronously in the code if there
  340.         /// subscribers available.
  341.         /// </summary>
  342.         virtual protected void RaiseOnClientConnectedEvent(IClient client)
  343.         {
  344.             // Obtain the lock to the events so we have exclusive access
  345.             // to the event handler.
  346.             lock (m_lock_event)
  347.             {
  348.                 // Copy the event handler to a local variable to prevent racing conditions
  349.                 // from breaking the code.
  350.                 EventHandler handler = m_event_connected;
  351.  
  352.                 // Check if the handler is not null, if it is not null it means there 
  353.                 // are subscribers availalbe for the event.
  354.                 if (handler != null)
  355.                     handler(client, new EventArgs());
  356.             }
  357.         }
  358.  
  359.         /// <summary>
  360.         /// Raises the OnClientDisconnected event synchronously in the code if there
  361.         /// are subscribers available.
  362.         /// </summary>
  363.         /// <param name="client">The client that has disconnected.</param>
  364.         virtual protected void RaiseOnClientDisconnectedEvent(IClient client)
  365.         { 
  366.             // Obtain the lock to the event so we have exclusive access 
  367.             // to the event handler.
  368.             lock (m_lock_event)
  369.             {
  370.                 // Copy the event handler to a local variable to prevent racing conditions
  371.                 // from breaking the code.
  372.                 EventHandler handler = m_event_disconnected;
  373.  
  374.                 // Check if the handler is not null, if it is not null it means there are
  375.                 // subscribers to the event.
  376.                 if (handler != null)
  377.                     handler(client, new EventArgs());
  378.             }
  379.         }
  380.  
  381.         /// <summary>
  382.         /// Cleans the result of an asynchronous callback and releases all the resources
  383.         /// used by the delegate of the callback.
  384.         /// </summary>
  385.         /// <param name="result"></param>
  386.         virtual protected void CleanCallBack(IAsyncResult result)
  387.         { 
  388.             // Cast the result back to a concrete result type to get the runtime delegate.
  389.             System.Runtime.Remoting.Messaging.AsyncResult aresult = result as System.Runtime.Remoting.Messaging.AsyncResult;
  390.  
  391.             // Clean the callback.
  392.             (aresult.AsyncDelegate as EventHandler<ErrorEventArgs>).EndInvoke(result);
  393.         }
  394.  
  395.         #endregion
  396.  
  397.         #region Private Fields
  398.  
  399.         private Socket m_socket;                                    // The socket of the server.
  400.         private Yarn m_yarn;                                        // The yarn that keeps track of the IFibers.
  401.         private readonly object m_lock_listensocket = new object(); // The lock to gain exclusive access to the socket.
  402.         private readonly object m_lock_yarn = new object();         // The lock to gain exclusive access to the yarn.
  403.         private readonly object m_lock_event = new object();        // The lock to gain exclusive access to the events.
  404.         private bool m_disposed = false;                            // Value indicating if the object has been disposed.
  405.         private int m_port;                                         // The port used to listen for incoming connections.
  406.         private int m_maxconnections;                               // The maximum number of connections allowed on the server.
  407.         private int m_interval;                                     // The interval in ms between listen operations.
  408.         private bool m_running = false;                             // Value indicating whether the server is running or not.
  409.         private Timer m_timer_listen;                               // Multithreaded timer that calls the listen routine.
  410.         private EventHandler m_event_connected;                     // Event to raise when a client connects.
  411.         private EventHandler m_event_disconnected;                  // Event to raise when a client disconnects.
  412.         private EventHandler<ClientDataEventArgs> m_event_data;     // Event to raise when a client sends data.
  413.         private EventHandler<ErrorEventArgs> m_event_error;         // Event to raise when an error occurs.
  414.  
  415.         #endregion
  416.     }
  417. }
2. The Fiber code. A fiber wraps an accepted client and polls it for data.
Expand|Select|Wrap|Line Numbers
  1.     public class Fiber : IFiber
  2.     {
  3.         #region Constructor
  4.  
  5.         /// <summary>
  6.         /// Creates a new instance of the TCPFiber class and assigns the values from the
  7.         /// parameters to the internal fields of the class.
  8.         /// </summary>
  9.         /// <param name="client">The IClient wrapped by the Fiber.</param>
  10.         public Fiber(IClient client)
  11.         { 
  12.             // Save the values in the internal fields.
  13.             Client = client;
  14.         }
  15.  
  16.         #endregion
  17.  
  18.         #region Public Properties
  19.  
  20.         /// <summary>
  21.         /// Gets or sets the IClient that is beeing wrapped & processed by the Fiber.
  22.         /// </summary>
  23.         public IClient Client
  24.         {
  25.             get { lock (m_lock_client) { return m_client; } }
  26.             set { lock (m_lock_client) { m_client = value; } }
  27.         }
  28.  
  29.         /// <summary>
  30.         /// Gets a value indicating if the Fiber is processing incoming data.
  31.         /// Readonly property.
  32.         /// </summary>
  33.         public bool Running
  34.         {
  35.             get { return m_running; }
  36.             protected set { m_running = value; }
  37.         }
  38.  
  39.         #endregion
  40.  
  41.         #region Public Events
  42.  
  43.         /// <summary>
  44.         /// This event gets raised by the Fiber when there is data from the client.
  45.         /// The event will contain the array of data, the client that raised the event
  46.         /// and the size of the data recieved.
  47.         /// </summary>
  48.         public event EventHandler<ClientDataEventArgs> OnData
  49.         {
  50.             add { lock (m_lock_event) { m_event_ondata += value; } }
  51.             remove { lock (m_lock_event) { m_event_ondata -= value; } }
  52.         }
  53.  
  54.         #endregion
  55.  
  56.         #region Public Methods
  57.  
  58.         /// <summary>
  59.         /// Disposes of the Fiber object and releases all managed and unmanaged resources.
  60.         /// </summary>
  61.         public void Dispose()
  62.         {
  63.             // Dispose of the managed and unmanaged resources in our class.
  64.             Dispose(true);
  65.  
  66.             // Suppress the finalization process of the GC to prevent undefined
  67.             // behavior during the cleaning of memory.
  68.             GC.SuppressFinalize(this);
  69.         }
  70.  
  71.         /// <summary>
  72.         /// Starts the Fiber to process incoming data from the underlying IClient and raise the
  73.         /// appropiate event every time there is data availalbe.
  74.         /// </summary>
  75.         /// <param name="delay">The amount of ms to wait before starting the first call.</param>
  76.         /// <param name="interval">The amount of ms between each subsequent call.</param>
  77.         public void Start(int delay, int interval)
  78.         {
  79.             // Create a new instance of the multithreaded timer to start the processing of
  80.             // the incoming data on the socket of the client.
  81.             m_processtimer = new Timer(new TimerCallback(ProcessRoutine), null, delay, interval);
  82.  
  83.             // Set the flag to true since the Fiber has been initiated.
  84.             Running = true;
  85.         }
  86.  
  87.         /// <summary>
  88.         /// Stops the Fiber to process data from the underlying IClient object.
  89.         /// </summary>
  90.         public void Stop()
  91.         {
  92.             // Dispose of the timer, so we dont have to process further data requests.
  93.             m_processtimer.Dispose();
  94.  
  95.             // Set the flag to false since the Fiber has been stopped.
  96.             Running = false;
  97.         }
  98.  
  99.         #endregion
  100.  
  101.         #region Private Methods
  102.  
  103.         /// <summary>
  104.         /// This function gets called on a regular interval to process the underlying client for incoming
  105.         /// data. If there is data to be read, the function will raise the OnData event.
  106.         /// </summary>
  107.         /// <param name="state">The state passed by the timer. Null in this case.</param>
  108.         protected virtual void ProcessRoutine(object state)
  109.         { 
  110.             // Try to obtain a lock on the client for exclusive access to the client.
  111.             // If the lock cannot be obtained, fall through the function because it
  112.             // means that another routine is still going.
  113.             if (Monitor.TryEnter(m_lock_client))
  114.             {
  115.                 // Now that we have the lock, we need to check if there is data
  116.                 // available on the client to read. Save this data in a seperate
  117.                 // variable because we will read a snapshot.
  118.                 int bytes_to_read = Client.DataAvailable;
  119.  
  120.                 // If there is data available, perform a read operation on the IClient
  121.                 // and raise the event. If there is no data available to read, fall 
  122.                 // through the function and try again on the next call.
  123.                 if (bytes_to_read > 0)
  124.                 {
  125.                     // Create a new buffer to hold the information. Perform the read
  126.                     // operation and use the return value of that operation to raise
  127.                     // the OnData event with the correct parameters.
  128.                     byte[] buffer = new byte[bytes_to_read];
  129.                     RaiseOnDataEvent(buffer, Client.Receive(buffer, 0, bytes_to_read));
  130.                 }
  131.             }
  132.         }
  133.  
  134.         /// <summary>
  135.         /// Internal function that diposed of all the resources claimed by the class.
  136.         /// Calling this function will completely destroy the object and release all 
  137.         /// the resources claimed by the class. All background threads and services
  138.         /// are beeing halted as well.
  139.         /// </summary>
  140.         /// <param name="disposeManagedResources">Value indicating if the managed resources need to be cleaned as well.</param>
  141.         protected virtual void Dispose(bool disposeManagedResources)
  142.         { 
  143.             // Only perform the disposed operation if we're not disposed of 
  144.             // already. Otherwise we'll get reference errors.
  145.             if (!m_disposed)
  146.             {
  147.                 // Check if we need to clean up the resources that are beeing
  148.                 // managed by the GarbageCollector.
  149.                 if (disposeManagedResources)
  150.                 {
  151.                     // Dispose all the managed resources.
  152.                     m_processtimer.Dispose();
  153.                     m_client.Disconnect();
  154.                     m_client.Dispose();
  155.                     OnData -= m_event_ondata;
  156.                 }
  157.  
  158.                 // Dispose of the unmanaged resources
  159.             }
  160.  
  161.             // Set the disposed flag to true.
  162.             m_disposed = true;
  163.         }
  164.  
  165.         /// <summary>
  166.         /// Raises the onData event of the Fiber with the supplied parameters.
  167.         /// If there are subscribers to the event, the event will be raised, if
  168.         /// there are no subscribers, the event is ignored by the function.
  169.         /// </summary>
  170.         /// <param name="data">The data read from the underlying IClient.</param>
  171.         /// <param name="size">The size of the data read from the IClient.</param>
  172.         private void RaiseOnDataEvent(byte[] data, int size)
  173.         {
  174.             // Obtain a lock on the event so we have short exclusive
  175.             // access to the event handler.
  176.             lock (m_lock_event)
  177.             {
  178.                 // Copy the event handler to a private variable to prevent racing 
  179.                 // conditions between the raising and unsubscribing of the event.
  180.                 EventHandler<ClientDataEventArgs> handler = m_event_ondata;
  181.  
  182.                 // Check if the handler is not null. If the handler is not null, it
  183.                 // means there are subscribers to the event and we can safely raise
  184.                 // the event.
  185.                 if (handler != null)
  186.                     handler(this, new ClientDataEventArgs(data, size));
  187.             }
  188.         }
  189.  
  190.         #endregion
  191.  
  192.         #region Private Fields
  193.  
  194.         private bool m_disposed = false;                            // Value indicating if the Fiber has been disposed of.
  195.         private bool m_running = false;                             // Value indicating if the Fiber is processing incomming data.
  196.         private readonly object m_lock_event = new object();        // Lock on the events of the Fiber.
  197.         private readonly object m_lock_client = new object();       // Lock on the client of the Fiber.
  198.         private EventHandler<ClientDataEventArgs> m_event_ondata;   // Eventhandler to raise the onData event.
  199.         private IClient m_client;                                   // IClient object beeing wrapped & processed.
  200.         private Timer m_processtimer;                               // Timer that fires the process routine on specified intervals.
  201.  
  202.         #endregion
  203.     }
  204.  
3. The client code. Used to talk to the server and is wrapped by the Fiber class.
Expand|Select|Wrap|Line Numbers
  1.     public class TCPClient : IClient
  2.     {
  3.         #region Constructor
  4.  
  5.         /// <summary>
  6.         /// Creates a new instance of the TCPClient class and assigns the parameter values
  7.         /// to the internal fields of the class.
  8.         /// </summary>
  9.         /// <param name="host">The remote host to establish a connection on.</param>
  10.         /// <param name="port">The remote port to establsih a connection on.</param>
  11.         public TCPClient(string host, int port)
  12.         { 
  13.             // Assign the parameters to the fields.
  14.             IP = host;
  15.             Port = port;
  16.             m_socket = null;
  17.         }
  18.  
  19.         /// <summary>
  20.         /// Creates a new instance of the TCPClient class and assigns the parameter values
  21.         /// to the internal fields of the class.
  22.         /// </summary>
  23.         /// <param name="socket">The socket on which to base the connection.</param>
  24.         public TCPClient(Socket socket)
  25.         {
  26.             // Assign the parameters to the fields.
  27.             m_socket = socket;
  28.             IP = (m_socket.RemoteEndPoint as IPEndPoint).Address.ToString();
  29.             Port = (m_socket.RemoteEndPoint as IPEndPoint).Port;
  30.         }
  31.  
  32.         #endregion
  33.  
  34.         #region Public Properties
  35.  
  36.         /// <summary>
  37.         /// Gets a value indicating if the TCPClient is currently connected to a remote location.
  38.         /// </summary>
  39.         public bool Connected
  40.         {
  41.             get { return ((m_socket == null) ? false : m_socket.Connected); }
  42.         }
  43.  
  44.         /// <summary>
  45.         /// Gets or sets the IPAddress of the remote host to which a connections needs to be established.
  46.         /// </summary>
  47.         public string IP
  48.         {
  49.             get { return m_ip; }
  50.             set { m_ip = value; }
  51.         }
  52.  
  53.         /// <summary>
  54.         /// Gets or sets the port of the remote host on which to establish a connection.
  55.         /// </summary>
  56.         public int Port
  57.         {
  58.             get { return m_port; }
  59.             set { m_port = value; }
  60.  
  61.         }
  62.  
  63.         /// <summary>
  64.         /// Gets the amount of data available on the internal socket to be read.
  65.         /// Retuns -1 if the socket is not available.
  66.         /// </summary>
  67.         /// <exception cref="System.Net.Sockets.SocketException">A problem occured accessing the underlying socket.</exception>
  68.         public int DataAvailable
  69.         {
  70.             get { return ((m_socket == null) ? -1 : m_socket.Available); }
  71.         }
  72.  
  73.         #endregion
  74.  
  75.         #region Public Methods
  76.  
  77.         /// <summary>
  78.         /// Establishes a connection to the remote host using the parameters of the class.
  79.         /// If the connection is succesfully established, the function will return true and
  80.         /// data can be received or transmitted.
  81.         /// </summary>
  82.         /// <returns>True if the connection attempt succeeds; otherwise false.</returns>
  83.         public bool Connect()
  84.         {
  85.             // Obtain a lock on the underlying socket for exclusive access during the
  86.             // entire connection attempt.
  87.             lock (m_lock_socket)
  88.             {
  89.                 // Check if the client is not connected already. We don't need to perform
  90.                 // a connection attempt if the client is already connected.
  91.                 if (!Connected)
  92.                 {
  93.                     // Surround the entire connection attempt with a try-catch statement
  94.                     // to prevent errors from breaking the code.
  95.                     try
  96.                     {
  97.                         // Create a new instance of the socket to connect to the remote
  98.                         // location.
  99.                         m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  100.                         m_socket.NoDelay = true;
  101.  
  102.                         // Try to establish the connection to the remote location.
  103.                         m_socket.Connect(IP, Port);
  104.  
  105.                         // If nothing went wrong, the function will return true at the end.
  106.                         RaiseOnConnectedEvent();
  107.                     }
  108.                     catch (ApplicationException ex)
  109.                     {
  110.                         // A problem occured while trying to establish the connection to the remote
  111.                         // host. Raise the onError event and exit the function.
  112.                         RaiseOnErrorEvent(ex);
  113.                         return false;
  114.                     }
  115.                 }
  116.  
  117.                 // Return true since the client is connected.
  118.                 return true;
  119.             }
  120.         }
  121.  
  122.         /// <summary>
  123.         /// Disconnects the TCPClient from the remote location and releases all internal resources
  124.         /// from the underlying socket.
  125.         /// </summary>
  126.         /// <returns>True if the TCPClient is properly disconnected from the remote location; otherwise false.</returns>
  127.         public bool Disconnect()
  128.         {
  129.             // Obtain a lock on the socket so we can perform the disconnect in a thread-safe environment.
  130.             lock (m_lock_socket)
  131.             {
  132.                 // Check if the client is actually connected. No need to perform the entire
  133.                 // disconnect attempt if the client is not connected.
  134.                 if (Connected)
  135.                 {
  136.                     // Surround the entire operation with a try-catch statement to prevent errors from
  137.                     // breaking the code.
  138.                     try
  139.                     {
  140.                         // Perform a shutdown first on the socket to prevent additional data to linger
  141.                         // in the buffers.
  142.                         m_socket.Shutdown(SocketShutdown.Both);
  143.  
  144.                         // Close the socket.
  145.                         m_socket.Close();
  146.  
  147.                         // If nothing went wrong the function will return true at the end.
  148.                         RaiseOnDisconnectedEvent();
  149.                     }
  150.                     catch (ApplicationException ex)
  151.                     {
  152.                         // An exception occured while performing the disconnect routine on the
  153.                         // socket. Raise the onError event.
  154.                         RaiseOnErrorEvent(ex);
  155.                         return false;
  156.                     }
  157.                 }
  158.  
  159.                 // Return true regardless if we performed the disconnect or not.
  160.                 return true;
  161.             }
  162.         }
  163.  
  164.         /// <summary>
  165.         /// Performs a read operation on the socket. If there is data available on the socket, the 
  166.         /// read operation will try to read out the specified block of data from the socket.
  167.         /// </summary>
  168.         /// <param name="buffer">The byte array to hold the data read from the socket.</param>
  169.         /// <param name="offset">The offset in the byte array at which the filling starts.</param>
  170.         /// <param name="length">The amount of bytes to read from the socket.</param>
  171.         /// <returns>The amount of bytes read from the socket.</returns>
  172.         public int Receive(byte[] buffer, int offset, int length)
  173.         {
  174.             // Obtain a lock on the socket to gain exclusive access to the socket.
  175.             lock (m_lock_socket)
  176.             {
  177.                 // Check if there is data available, If there is no data available, 
  178.                 // exit the function.
  179.                 if (DataAvailable > 0)
  180.                 {
  181.                     // There is information available. Perform a read operation on the socket
  182.                     // and return the amount of bytes read.
  183.                     return m_socket.Receive(buffer, offset, length, SocketFlags.None);
  184.                 }
  185.                 else
  186.                 {
  187.                     // No data to read, so return 0.
  188.                     return 0;
  189.                 }
  190.             }
  191.         }
  192.  
  193.         /// <summary>
  194.         /// Performs a send operation on the underlying socket to transmit data to the remote host.
  195.         /// The function will try to send as much data as possible in a single go.
  196.         /// </summary>
  197.         /// <param name="data">the data as a byte array that needs to be sent.</param>
  198.         /// <param name="offset">the offset in the data array at which the sending begins</param>
  199.         /// <param name="length">The length of the data to send.</param>
  200.         /// <returns>The amount of bytes that have been sent.</returns>
  201.         public int Send(byte[] data, int offset, int length)
  202.         {
  203.             // Obtain a lock on the socket to gain exclusive access to the socket.
  204.             lock (m_lock_socket)
  205.             {
  206.                 // Surround the write operation with a try-catch statement to prevent
  207.                 // errors from breaking the code.
  208.                 try
  209.                 {
  210.                     // Try to send that data and return the amount of bytes
  211.                     // actually sent.
  212.                     return m_socket.Send(data, offset, length, SocketFlags.None);
  213.                 }
  214.                 catch (ApplicationException ex)
  215.                 {
  216.                     // An excepton occured while sending the data. Raise the event
  217.                     // and return 0.
  218.                     RaiseOnErrorEvent(ex);
  219.                     return 0;
  220.                 }
  221.             }
  222.         }
  223.  
  224.         /// <summary>
  225.         /// Disposes the TCPClient and all the internal resources.
  226.         /// </summary>
  227.         public void Dispose()
  228.         {
  229.             // Dispose of ourselves including the managed resources.
  230.             Dispose(true);
  231.  
  232.             // Suppress the GC.
  233.             GC.SuppressFinalize(this);
  234.         }
  235.  
  236.         #endregion
  237.  
  238.         #region Events
  239.  
  240.         /// <summary>
  241.         /// This event gets fired when the Client successfully establishes a connection to the remote location.
  242.         /// </summary>
  243.         public event EventHandler OnConnect
  244.         {
  245.             add { lock (m_lock_event) { m_event_connect += value; } }
  246.             remove { lock (m_lock_event) { m_event_connect -= value; } }
  247.         }
  248.  
  249.         /// <summary>
  250.         /// This event gets fired when the Client successfully disconnects from the remote location.
  251.         /// </summary>
  252.         public event EventHandler OnDisconnct
  253.         {
  254.             add { lock (m_lock_event) { m_event_disconnect += value; } }
  255.             remove { lock (m_lock_event) { m_event_disconnect -= value; } }
  256.         }
  257.  
  258.         /// <summary>
  259.         /// This event gets fired when the client encounters an internal error.
  260.         /// </summary>
  261.         public event EventHandler<ErrorEventArgs> OnError
  262.         {
  263.             add { lock (m_lock_event) { m_event_error += value; } }
  264.             remove { lock (m_lock_event) { m_event_error -= value; } }
  265.         }
  266.  
  267.         #endregion
  268.  
  269.         #region Private Methods
  270.  
  271.         /// <summary>
  272.         /// Raises the onError event asynchronously.
  273.         /// </summary>
  274.         /// <param name="ex">The Exception that triggered the event.</param>
  275.         private void RaiseOnErrorEvent(ApplicationException ex)
  276.         { 
  277.             // use the lock to gain exclusive access to the event handler.
  278.             lock (m_lock_event)
  279.             {
  280.                 // Copy the eventhandler to a local variable to prevent racing conditions.
  281.                 EventHandler<ErrorEventArgs> handler = m_event_error;
  282.  
  283.                 // Raise the event asynchronously if possible.
  284.                 if (handler != null)
  285.                     handler.BeginInvoke(this, new ErrorEventArgs(ex), new AsyncCallback(CleanCallbackResult), null);
  286.             }
  287.         }
  288.  
  289.         /// <summary>
  290.         /// Raises the onConnected event.
  291.         /// </summary>
  292.         private void RaiseOnConnectedEvent()
  293.         { 
  294.             // Use the lock to gain exclusive access to the event handler.
  295.             lock (m_lock_event)
  296.             {
  297.                 // Copy the event handler to prevent racing conditions.
  298.                 EventHandler handler = m_event_connect;
  299.  
  300.                 // Raise the eventhandler if possible
  301.                 if (handler != null)
  302.                     handler(this, new EventArgs());
  303.             }
  304.         }
  305.  
  306.         /// <summary>
  307.         /// Raises the onDisconnected event.
  308.         /// </summary>
  309.         private void RaiseOnDisconnectedEvent()
  310.         {
  311.             // Use the lock to gain exclusive access to the event handler.
  312.             lock (m_lock_event)
  313.             {
  314.                 // Copy the event handler to prevent racing conditions.
  315.                 EventHandler handler = m_event_disconnect;
  316.  
  317.                 // Raise the eventhandler if possible
  318.                 if (handler != null)
  319.                     handler(this, new EventArgs());
  320.             }
  321.         }
  322.  
  323.         /// <summary>
  324.         /// Cleans the result of the asynchronous callback event of our onError event.
  325.         /// </summary>
  326.         /// <param name="result">The result of the callback.</param>
  327.         private void CleanCallbackResult(IAsyncResult result)
  328.         {
  329.             // Cast the received result to an AsyncResult so we can extract the delegate.
  330.             System.Runtime.Remoting.Messaging.AsyncResult aresult = result as System.Runtime.Remoting.Messaging.AsyncResult;
  331.  
  332.             // Extract the delegate and clean the callback.
  333.             (aresult.AsyncDelegate as EventHandler<ErrorEventArgs>).EndInvoke(result);
  334.         }
  335.  
  336.         /// <summary>
  337.         /// Performs the actuall dispose request and releases all resources used
  338.         /// by the managed and unmanaged parts of the code.
  339.         /// </summary>
  340.         /// <param name="disposeManagedResources">Value indicating to release managed resources as well.</param>
  341.         protected void Dispose(bool disposeManagedResources)
  342.         {
  343.             // Check if we're already disposed. Nothing to do if we're disposed.
  344.             if (!m_disposed)
  345.             {
  346.                 // Check if we need to dispose the managed resources.
  347.                 if (disposeManagedResources)
  348.                 {
  349.                     // Dispose our events first.
  350.                     OnConnect -= m_event_connect;
  351.                     OnDisconnct -= m_event_disconnect;
  352.                     OnError -= m_event_error;
  353.  
  354.                     // Dispose of the socket.
  355.                     Disconnect();
  356.                 }
  357.  
  358.                 // Dispose of the unmanaged resources.
  359.             }
  360.  
  361.             // Change the disposed flag.
  362.             m_disposed = true;
  363.         }
  364.  
  365.         #endregion
  366.  
  367.         #region Private Fields
  368.  
  369.         private string m_ip;                                    // Remote host.
  370.         private int m_port;                                     // Remote port.
  371.         private Socket m_socket;                                // The underlying socket.
  372.         private EventHandler m_event_connect;                   // Event fired when the client connects.
  373.         private EventHandler m_event_disconnect;                // Event fired when the client disconnets.
  374.         private EventHandler<ErrorEventArgs> m_event_error;     // Event fired when an internal error occurs.
  375.         private readonly object m_lock_event = new object();    // Lock for exclusive access to the events.
  376.         private readonly object m_lock_socket = new object();   // Lock for exclusive access to the underlying socket.
  377.         private bool m_disposed = false;                        // Value indicating if the object has been disposed.
  378.  
  379.         #endregion
  380.     }
  381.  
4. Yarn code. Basic wrapper around a list for multihtreaded access. Hold all the fibers for the server.
Expand|Select|Wrap|Line Numbers
  1.     public class Yarn : IList<IFiber>, IDisposable
  2.     {
  3.         #region Constructor
  4.  
  5.         /// <summary>
  6.         /// Creates a new instance of the Yarn class with the specified collection to use as
  7.         /// internal storage mechanism.
  8.         /// </summary>
  9.         /// <param name="collection">The IList implementation to use as internal storage for the IFiber objects.</param>
  10.         public Yarn(IList<IFiber> collection)
  11.         {
  12.             // Assign the collection to the field.
  13.             m_fibers = collection;
  14.         }
  15.  
  16.         #endregion
  17.  
  18.         #region Public Properties
  19.  
  20.         /// <summary>
  21.         /// Gets or sets the IFiber at the specific index.
  22.         /// </summary>
  23.         /// <param name="index">The zero-based index of the IFiber.</param>
  24.         /// <returns>The IFiber at the specified index.</returns>
  25.         public IFiber this[int index]
  26.         {
  27.             get { lock (m_lock) { return m_fibers[index]; } }
  28.             set { lock (m_lock) { m_fibers[index] = value; } }
  29.         }
  30.  
  31.         #endregion
  32.  
  33.         #region Public Methods
  34.  
  35.         /// <summary>
  36.         /// Disposes of the Yarn and all the internal objects.
  37.         /// </summary>
  38.         public void Dispose()
  39.         {
  40.             // Clean ourselves and all our internal objects.
  41.             Dispose(true);
  42.  
  43.             // Supress the GC.
  44.             GC.SuppressFinalize(this);
  45.         }
  46.  
  47.         /// <summary>
  48.         /// Determines the index of a specific IFiber in the Yarn.
  49.         /// </summary>
  50.         /// <param name="item">The specific IFiber to locate in the Yarn.</param>
  51.         /// <returns>The index of the specific IFiber.</returns>
  52.         public int IndexOf(IFiber item)
  53.         {
  54.             lock (m_lock) { return m_fibers.IndexOf(item); }
  55.         }
  56.  
  57.         /// <summary>
  58.         /// Inserts an IFiber into the Yarn at the specific location.
  59.         /// </summary>
  60.         /// <param name="index">The location in the Yarn to insert the IFiber.</param>
  61.         /// <param name="item">The IFiber to insert into the Yarn.</param>
  62.         public void Insert(int index, IFiber item)
  63.         {
  64.             lock (m_lock) { m_fibers.Insert(index, item); }
  65.         }
  66.  
  67.         /// <summary>
  68.         /// Removes the IFiber at the specific index.
  69.         /// </summary>
  70.         /// <param name="index">The index at which to remove the IFiber.</param>
  71.         public void RemoveAt(int index)
  72.         {
  73.             lock (m_lock) { m_fibers.RemoveAt(index); }
  74.         }
  75.  
  76.  
  77.         /// <summary>
  78.         /// Adds the specific IFiber to the Yarn.
  79.         /// </summary>
  80.         /// <param name="item">The IFiber to add to the Yarn.</param>
  81.         public void Add(IFiber item)
  82.         {
  83.             lock (m_lock) { m_fibers.Add(item); }
  84.         }
  85.  
  86.         /// <summary>
  87.         /// Removes all IFibers from the Yarn
  88.         /// </summary>
  89.         public void Clear()
  90.         {
  91.             lock (m_lock) { m_fibers.Clear(); }
  92.         }
  93.  
  94.         /// <summary>
  95.         /// Checks if a specific IFiber is part of the Yarn.
  96.         /// </summary>
  97.         /// <param name="item">The specific IFiber to look for.</param>
  98.         /// <returns>True if the specific IFiber is found; otherwise false.</returns>
  99.         public bool Contains(IFiber item)
  100.         {
  101.             lock (m_lock) { return m_fibers.Contains(item); }
  102.         }
  103.  
  104.         /// <summary>
  105.         /// Copies the entire Yarn into the specified array at the specified index.
  106.         /// </summary>
  107.         /// <param name="array">The array to copy the Yarn into.</param>
  108.         /// <param name="arrayIndex">The index in the array at which the coying starts.</param>
  109.         public void CopyTo(IFiber[] array, int arrayIndex)
  110.         {
  111.             lock (m_lock) { m_fibers.CopyTo(array, arrayIndex); }
  112.         }
  113.  
  114.         /// <summary>
  115.         /// Returns the number of IFibers in the Yarn.
  116.         /// </summary>
  117.         public int Count
  118.         {
  119.             get { lock (m_lock) { return m_fibers.Count; } }
  120.         }
  121.  
  122.         /// <summary>
  123.         /// Returns a value indicating if the Yarn is marked as read-only.
  124.         /// </summary>
  125.         public bool IsReadOnly
  126.         {
  127.             get { return false; }
  128.         }
  129.  
  130.         /// <summary>
  131.         /// Removes a specific IFiber from the Yarn.
  132.         /// </summary>
  133.         /// <param name="item">The specific IFiber to remove from the Yarn.</param>
  134.         /// <returns>True if the IFiber got removed successfully; otherwise false.</returns>
  135.         public bool Remove(IFiber item)
  136.         {
  137.             lock (m_lock) { return m_fibers.Remove(item); }
  138.         }
  139.  
  140.         /// <summary>
  141.         /// Returns the enumerator to browse through the Yarn.
  142.         /// </summary>
  143.         /// <returns>The enumerator to browse through the Yarn</returns>
  144.         public IEnumerator<IFiber> GetEnumerator()
  145.         {
  146.             lock (m_lock) { return ((IEnumerator<IFiber>)m_fibers.GetEnumerator()); }
  147.         }
  148.  
  149.         /// <summary>
  150.         /// Returns the enumerator to browse through the Yarn.
  151.         /// </summary>
  152.         /// <returns>The enumerator to browse through the Yarn</returns>
  153.         System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
  154.         {
  155.             lock (m_lock) { return m_fibers.GetEnumerator(); }
  156.         }
  157.  
  158.         #endregion
  159.  
  160.         #region Private Methods
  161.  
  162.         /// <summary>
  163.         /// Performs the disposing operation on the internal objects.
  164.         /// </summary>
  165.         /// <param name="disposeManagedResources">Value indicating if the managed resources need to be disposed off.</param>
  166.         protected void Dispose(bool disposeManagedResources)
  167.         {
  168.             // Check if we're already disposed or still need to clean ourselves.
  169.             if (!m_disposed)
  170.             {
  171.                 // Check if we need to dispose our managed resources.
  172.                 if (disposeManagedResources)
  173.                 {
  174.                     // First kick all clients and dispose of them.
  175.                     foreach (IFiber f in m_fibers)
  176.                         f.Dispose();
  177.  
  178.                     // After all are cleared, remove the list of entries.
  179.                     Clear();
  180.                 }
  181.  
  182.                 // Dispose of unmagaged resources.
  183.             }
  184.  
  185.             // Set our disposed flag to true.
  186.             m_disposed = true;
  187.         }
  188.  
  189.         #endregion
  190.  
  191.         #region Private Fields
  192.  
  193.         private IList<IFiber> m_fibers;                 // The internal list of fibers beeing handled by this yarn.
  194.         private readonly object m_lock = new object();  // Object to lock upon for exlusive access to the Fibers.
  195.         private bool m_disposed = false;                // Value indicating if the object has been disposed of.
  196.  
  197.         #endregion        
  198.     }
  199.  
I know it's a rather big question, but I'm so close to making my own TCPserver & Client in C# that I really wanne get it done this time.
Aug 24 '10 #1
1 3365
Airslash
221 New Member
I found it \o/

I changed the property DataAvailable on the TCPClient into this

Expand|Select|Wrap|Line Numbers
  1.         /// <summary>
  2.         /// Gets the amount of data available on the internal socket to be read.
  3.         /// Retuns -1 if the socket is not available.
  4.         /// </summary>
  5.         /// <exception cref="System.Net.Sockets.SocketException">A problem occured accessing the underlying socket.</exception>
  6.         public int DataAvailable
  7.         {
  8.             // Check if the socket exists, and has data on the socket avaialble.
  9.             get { return ((m_socket == null) ? -2 : ((m_socket.Poll(10000, SelectMode.SelectRead)) ? m_socket.Available : -1)); }
  10.         }
  11.  
and now it works like a charm. Made a silly logic error........I' m such a nubcake.
Here is the debug output of the code:

Client has connected to the server. Remote IP : 127.0.0.1, remote port: 8000
Client has connected to the server. Remote IP : 127.0.0.1, remote port: 2023
Sending HELLO over the client socket...
HELLO has been transmitted over the socket...
Client send the data to us: HELLO
Client has disconnected from the server. Remote IP : 127.0.0.1, remote port: 8000


p.s: Anyone can use this code, but I'd love it if people added a reference in it where they got it from.
Aug 24 '10 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

0
2346
by: anuradha.k.r | last post by:
hi, I 'v e written both the server and client side socket programs in perl( a very small one).My socket is created and shows that the connection is established with the client.however I am not able to receive data in server side.I think the client sends the data properly.Somehow receive does not happen. Can someone tell me what could be wrong? My code is part of the sample programs available for socket prgmng in the net. Here is the...
1
3787
by: Daniel | last post by:
after opening socket, sending data then closing socket 3000 times i get "Only one usage of each socket address" what am i doing wrong? is there some thing else i need to do to free up the socket after i send data into it? I simply want to open socket, send data, close socket and have the server just handle one client thread to recieve connection, recieve data, and close socket
2
2896
by: Brett B | last post by:
I just installed mysql on linux. If I open a terminal, su to root, then type "mysql", I am able to connect to the server and run my queries. If I exit out of su so that I am my own id (baisley) and type "mysql", I get this error: Can't connect to local MySQL server through socket '/home/data/mysql/mysql.sock' (13) Any idea why? mysql.sock has full permissions (read/write/execute), so it should be accessable by user baisley. If I am...
2
7563
by: Ben | last post by:
I need to send data from a client to a server. In the server code I have: s = ServerSocket.Accept() If (s.Connected = False) Then MsgBox("Unable to connect", , "Server Error") Exit Sub End If While (s.Connected = True)
1
2941
by: atefe | last post by:
hi,every one i want to transmit data from a pic microcontroller to a pc . i need visual basic 6 codes for receiving data. would you mind helping me? thanks alot
2
4309
by: pauland80 | last post by:
Hello, My soft passively listen to a device sending +- 300 bytes of data each second. After several hours of work, the soft abruptly stops receiving data without any error, (while the device sends properly, of course) and I need to restart it (the python soft) to "reactivate" the ports. I read that when the serial port encounters an error (frame error or so, I imagine?) it stop receiving data until the library function...
8
16535
by: dadalos | last post by:
Hello; I'm having a problem with receiving data from serial port. There's an eventhandler(datareceived) and I'm monitoring the answer from the serial port to a text box in the eventhandler. There's no problem till here. But also I want to use the incoming data to process it in some functions. But when I assign the incoming string(from the ReadExisting() function) to a local variable there are always lots of characters missing. How do I solve...
7
3176
by: darthghandi | last post by:
I am having mixed results with asynchronous socket receives. Sometimes I get the right information back from the buffer, other times I get some of the data that should be in the buffer printed out to the console. That data is printed out to the console before I even call Socket.EndReceive(). After that call, I get the rest of the data that wasn't printed out to the console in the buffer. Anyone have any idea what is going on? Here's...
0
3573
by: george585 | last post by:
Hello! I am new to network programming, and understand just basics. Using some sample code, and having read documentation, I managed to create a simple app in C# and VB.NET. The application is supposed to do the following: monitor ALL INCOMING TCP traffic on the local computer, and save certain parts of it as files - not log files though, but actual files that are sent to the computer as part of http or ftp. Basically if a user browse a page...
10
34489
by: John Salerno | last post by:
I wrote some pretty basic socket programming again, but I'm still confused about what's happening with the buffer_size variable. Here are the server and client programs: -------------- from socket import * host = '' port = 51567 address = (host, port) buffer_size = 1024
0
8384
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8302
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8718
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8601
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7314
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5630
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4300
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2726
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1937
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.