using System; using System.Net; using System.Net.Sockets; using System.Collections.Generic; using Woodpecker.Core; namespace Woodpecker.Net.Remote { /// /// Provides various methods for interacting with Woodpecker via a remote connection, eg, for housekeeping purposes. /// public partial class remoteConnectionManager { #region Fields /// /// The System.Net.Sockets.Socket object that listens for connections. /// private Socket mListener; /// /// A List of the type Socket with the Sockets that have connected and haven't send a message yet. /// private List mClients = new List(); #endregion #region Methods /// /// Attempts to start listening on a certain port. A boolean that indicates if the operation has succeeded is returned. /// /// The TCP port number to listen on. /// Supply true if the server can accept connections from different hosts than just localhost. public bool startListening(int Port, bool allowExternalHosts) { try { mListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint EP = null; if (allowExternalHosts) EP = new IPEndPoint(IPAddress.Any, Port); else EP = new IPEndPoint(IPAddress.Loopback, Port); mListener.Bind(EP); mListener.Listen(4); mListener.BeginAccept(new AsyncCallback(connectionRequest), mListener); Logging.Log("Remote connection listener running on port " + Port + ", allow external hosts: " + allowExternalHosts.ToString().ToLower() + "."); return true; } catch { return false; } } /// /// Stops listening for connections. /// public void stopListening() { try { mListener.Close(); mListener = null; } catch { } } /// /// Invoked asynchronously when a new client requests connection. /// /// The IAsyncResult object of the asynchronous BeginAccept operation. private void connectionRequest(IAsyncResult iAr) { try { Socket Request = mListener.EndAccept(iAr); remoteConnection newClient = new remoteConnection(Request); newClient.waitForData(); } catch { } finally { if (mListener != null) mListener.BeginAccept(new AsyncCallback(this.connectionRequest), mListener); } } #endregion } }